diff --git a/Build/build-functions.psm1 b/Build/build-functions.psm1 index d033a06448..e5f71964bf 100644 --- a/Build/build-functions.psm1 +++ b/Build/build-functions.psm1 @@ -28,7 +28,7 @@ function Update-GeneratedCode { write-host -foreground blue "Generate code...END`n" } -function Start-Build([boolean] $IncludeWindowsRuntimeComponent = $false, [boolean] $IncludeNanoFramework = $false) { +function Start-Build([boolean] $IncludeNanoFramework = $false) { write-host -foreground blue "Start-Build...`n---" $fileLoggerArg = "/logger:FileLogger,Microsoft.Build;logfile=$testReportDir\UnitsNet.msbuild.log" @@ -40,24 +40,6 @@ function Start-Build([boolean] $IncludeWindowsRuntimeComponent = $false, [boolea dotnet build --configuration Release "$root\UnitsNet.sln" $fileLoggerArg $appVeyorLoggerArg if ($lastexitcode -ne 0) { exit 1 } - if (-not $IncludeWindowsRuntimeComponent) - { - write-host -foreground yellow "Skipping WindowsRuntimeComponent build." - } - else - { - write-host -foreground green "Build WindowsRuntimeComponent." - $fileLoggerArg = "/logger:FileLogger,Microsoft.Build;logfile=$testReportDir\UnitsNet.WindowsRuntimeComponent.msbuild.log" - $appVeyorLoggerArg = if (Test-Path "$appVeyorLoggerDll") { "/logger:$appVeyorLoggerDll" } else { "" } - - # dontnet CLI does not support WindowsRuntimeComponent project type yet - # msbuild does not auto-restore nugets for this project type - write-host -foreground yellow "WindowsRuntimeComponent project not yet supported by dotnet CLI, using MSBuild15 instead" - & "$msbuild" "$root\UnitsNet.WindowsRuntimeComponent.sln" /verbosity:minimal /p:Configuration=Release /t:restore - & "$msbuild" "$root\UnitsNet.WindowsRuntimeComponent.sln" /verbosity:minimal /p:Configuration=Release $fileLoggerArg $appVeyorLoggerArg - if ($lastexitcode -ne 0) { exit 1 } - } - if (-not $IncludeNanoFramework) { write-host -foreground yellow "Skipping .NET nanoFramework build." @@ -82,8 +64,7 @@ function Start-Tests { $projectPaths = @( "UnitsNet.Tests\UnitsNet.Tests.csproj", "UnitsNet.NumberExtensions.Tests\UnitsNet.NumberExtensions.Tests.csproj", - "UnitsNet.Serialization.JsonNet.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj", - "UnitsNet.Serialization.JsonNet.CompatibilityTests\UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj" + "UnitsNet.Serialization.JsonNet.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj" ) # Parent dir must exist before xunit tries to write files to it @@ -129,21 +110,13 @@ function Start-PackNugets { if ($lastexitcode -ne 0) { exit 1 } } - if (-not $IncludeWindowsRuntimeComponent) { - write-host -foreground yellow "Skipping WindowsRuntimeComponent nuget pack." - } else { - write-host -foreground yellow "WindowsRuntimeComponent project not yet supported by dotnet CLI, using nuget.exe instead" - & $nuget pack "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" - } - if (-not $IncludeNanoFramework) { write-host -foreground yellow "Skipping nanoFramework nuget pack." } else { write-host -foreground yellow "nanoFramework project not yet supported by dotnet CLI, using nuget.exe instead" - Invoke-Build-NanoNugets + Invoke-BuildNanoNugets } - write-host -foreground blue "Pack nugets...END`n" } diff --git a/Build/build-pack-nano-nugets.psm1 b/Build/build-pack-nano-nugets.psm1 index 7ff831deba..5a3d940f4f 100644 --- a/Build/build-pack-nano-nugets.psm1 +++ b/Build/build-pack-nano-nugets.psm1 @@ -2,7 +2,7 @@ $nugetOutDir = "$root\Artifacts\NuGet" $nuget = "$root\Tools\NuGet.exe" -function Invoke-Build-NanoNugets { +function Invoke-BuildNanoNugets { & $nuget pack "$root\UnitsNet.NanoFramework\GeneratedCode\Duration\UnitsNet.NanoFramework.Duration.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" & $nuget pack "$root\UnitsNet.NanoFramework\GeneratedCode\ElectricCurrent\UnitsNet.NanoFramework.ElectricCurrent.nuspec" -Verbosity detailed -OutputDirectory "$nugetOutDir" @@ -25,4 +25,4 @@ function Invoke-Build-NanoNugets { } -export-modulemember -function Invoke-Build-NanoNugets +export-modulemember -function Invoke-BuildNanoNugets diff --git a/Build/build.ps1 b/Build/build.ps1 index 0c5e087474..36b6169636 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -7,12 +7,9 @@ Publishing nugets is handled by nuget-publish.bat and run by the build server on the master branch. -.PARAMETER skipUWP - If flag is set, will skip the UWP (Windows Runtime Component) build step as this requires - some large, extra Visual Studio features to be installed. .EXAMPLE powershell ./build.ps1 - powershell ./build.ps1 -IncludeWindowsRuntimeComponent -IncludeNanoFramework + powershell ./build.ps1 -IncludeNanoFramework .NOTES Author: Andreas Gullberg Larsen @@ -20,7 +17,6 @@ #> [CmdletBinding()] Param( - [switch] $IncludeWindowsRuntimeComponent, [switch] $IncludeNanoFramework ) @@ -32,7 +28,7 @@ try { Remove-ArtifactsDir Update-GeneratedCode - Start-Build -IncludeWindowsRuntimeComponent $IncludeWindowsRuntimeComponent -IncludeNanoFramework $IncludeNanoFramework + Start-Build -IncludeNanoFramework $IncludeNanoFramework Start-Tests Start-PackNugets Compress-ArtifactsAsZip diff --git a/Build/init.ps1 b/Build/init.ps1 index 6892afbe76..9cb026c04a 100644 --- a/Build/init.ps1 +++ b/Build/init.ps1 @@ -68,19 +68,24 @@ if (!(Test-Path "$msbuildPath/nanoFramework")) { $extensionVersion = $vs2019Tag } - Write-Output "Downloading visx..." -NoNewline + Write-Output "Downloading visx..." # download VS extension - Write-Debug "Download VSIX file from $extensionUrl to $vsixPath" + Write-Host "Download VSIX file from $extensionUrl to $vsixPath" $webClient.DownloadFile($extensionUrl, $vsixPath) $outputPath = "$tempDir\nf-extension" $vsixPath = Join-Path -Path $tempDir -ChildPath "nf-extension.zip" - $webClient.DownloadFile($extensionUrl,$vsixPath) - Expand-Archive -LiteralPath $vsixPath -DestinationPath $outputPath | Write-Host + $webClient.DownloadFile($extensionUrl, $vsixPath) + + Write-Host "Extract VSIX file to $outputPath" + Expand-Archive -LiteralPath $vsixPath -DestinationPath $outputPath -Force | Write-Host + + $copyFrom = "$outputPath\`$MSBuild\nanoFramework" - Copy-Item -Path "$outputPath\`$MSBuild\nanoFramework" -Destination $msbuildPath -Recurse + Write-Host "Copy from $copyFrom to $msbuildPath" + Copy-Item -Path "$copyFrom" -Destination $msbuildPath -Recurse Write-Host "Installed VS extension $extensionVersion" } diff --git a/Build/set-version-UnitsNet.ps1 b/Build/set-version-UnitsNet.ps1 index d2908b1221..b4c0e10f65 100644 --- a/Build/set-version-UnitsNet.ps1 +++ b/Build/set-version-UnitsNet.ps1 @@ -55,8 +55,6 @@ $projFile = "$root\UnitsNet\UnitsNet.csproj" $numberExtensionsProjFile = "$root\UnitsNet.NumberExtensions\UnitsNet.NumberExtensions.csproj" $nanoFrameworkNuspecGeneratorFile = "$root\CodeGen\Generators\NanoFrameworkGen\NuspecGenerator.cs" $nanoFrameworkAssemblyInfoFile = "$root\UnitsNet.NanoFramework\GeneratedCode\Properties\AssemblyInfo.cs" -$winrtAssemblyInfoFile = "$root\UnitsNet.WindowsRuntimeComponent\Properties\AssemblyInfo.cs" -$winrtNuspecFile = "$root\UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.nuspec" # Use UnitsNet.Common.props version as base if bumping major/minor/patch $newVersion = Get-NewProjectVersion $projFile $paramSet $setVersion $bumpVersion @@ -68,15 +66,9 @@ $didStash = Invoke-StashPush Set-ProjectVersion $projFile $newVersion Set-ProjectVersion $numberExtensionsProjFile $newVersion -# Update AssemblyInfo.cs files -Set-AssemblyInfoVersion $winrtAssemblyInfoFile $newVersion - # Update AssemblyInfo.cs file for .NET nanoFramework Set-AssemblyInfoVersion $nanoFrameworkAssemblyInfoFile $newVersion -# Update .nuspec files -Set-NuspecVersion $winrtNuspecFile $newVersion - # Update codegen and .nuspec files for nanoFramework Set-NuspecVersion $nanoFrameworkNuspecGeneratorFile $newVersion Get-ChildItem -Path "$root\UnitsNet.NanoFramework\GeneratedCode" -Include '*.nuspec' -Recurse | diff --git a/Build/set-version-json.sh b/Build/set-version-json.sh new file mode 100644 index 0000000000..aa2e9f342c --- /dev/null +++ b/Build/set-version-json.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Sets version of nuget UnitNets.Serialization.JsonNet. +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +set_version_script="$script_dir/set-version-UnitsNet.Serialization.JsonNet.ps1" + +if [ $# -eq 1 ]; then + powershell -NoProfile $set_version_script -setVersion $1 + exit 0 +else + echo "Usage: ./set-version-json.sh " + echo "" + echo "Examples:" + echo "$ ./set-version-json.sh 5.0.0-alpha001" + echo "$ ./set-version-json.sh 5.1.2" + exit 1 +fi \ No newline at end of file diff --git a/CodeGen/CodeGen.csproj b/CodeGen/CodeGen.csproj index b90e8237a5..4ecc7cd856 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp5.0 + netcoreapp6.0 latest enable diff --git a/CodeGen/Generators/GeneratorBase.cs b/CodeGen/Generators/GeneratorBase.cs index 53c9a23f7f..8488e5baae 100644 --- a/CodeGen/Generators/GeneratorBase.cs +++ b/CodeGen/Generators/GeneratorBase.cs @@ -7,10 +7,9 @@ namespace CodeGen.Generators { internal abstract class GeneratorBase { - protected readonly MyTextWriter Writer = new MyTextWriter(); - public abstract string Generate(); + protected readonly MyTextWriter Writer = new(); - public const string GeneratedFileHeader = @"//------------------------------------------------------------------------------ + protected const string GeneratedFileHeader = @"//------------------------------------------------------------------------------ // // This code was generated by \generate-code.bat. // diff --git a/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs index 15274f190a..5d1cf278e4 100644 --- a/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs @@ -19,13 +19,13 @@ public NuspecGenerator( _mathNuGetVersion = mathNuGetVersion; } - public override string Generate() + public string Generate() { Writer.WL($@" UnitsNet.nanoFramework.{_quantity.Name} - 4.149.0 + 5.0.0-alpha006 Units.NET {_quantity.Name} - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -38,7 +38,7 @@ public override string Generate() Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component {_quantity.Name.ToLower()} + nanoframework {_quantity.Name.ToLower()} unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable "); diff --git a/CodeGen/Generators/NanoFrameworkGen/ProjectGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/ProjectGenerator.cs index ce5e457934..4a9503df5d 100644 --- a/CodeGen/Generators/NanoFrameworkGen/ProjectGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/ProjectGenerator.cs @@ -14,7 +14,7 @@ public ProjectGenerator(Quantity quantity, NanoFrameworkVersions versions) _versions = versions; } - public override string Generate() + public string Generate() { Writer.WL($@" diff --git a/CodeGen/Generators/NanoFrameworkGen/PropertyGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/PropertyGenerator.cs index f046e72ca2..1d235b79ac 100644 --- a/CodeGen/Generators/NanoFrameworkGen/PropertyGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/PropertyGenerator.cs @@ -13,7 +13,7 @@ public PropertyGenerator(string version) _version = version; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.W($@"using System.Reflection; diff --git a/CodeGen/Generators/NanoFrameworkGen/QuantityGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/QuantityGenerator.cs index 20c9589c7a..2426f90930 100644 --- a/CodeGen/Generators/NanoFrameworkGen/QuantityGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/QuantityGenerator.cs @@ -17,7 +17,7 @@ public QuantityGenerator(Quantity quantity) _unitEnumName = $"{quantity.Name}Unit"; } - public override string Generate() + public string Generate() { // Auto generated header Writer.WL(GeneratedFileHeader); @@ -30,7 +30,7 @@ namespace UnitsNet Writer.WL($@" /// /// - /// {_quantity.XmlDoc} + /// {_quantity.XmlDocSummary} /// "); Writer.WLCondition(_quantity.XmlDocRemarks.HasText(), $@" @@ -44,7 +44,7 @@ public struct {_quantity.Name} /// /// The numeric value this quantity was constructed with. /// - private readonly {_quantity.BaseType} _value; + private readonly {_quantity.ValueType} _value; /// /// The unit this quantity was constructed with. @@ -54,7 +54,7 @@ public struct {_quantity.Name} /// /// The numeric value this quantity was constructed with. /// - public {_quantity.BaseType} Value => _value; + public {_quantity.ValueType} Value => _value; /// public {_unitEnumName} Unit => _unit; @@ -67,7 +67,7 @@ public struct {_quantity.Name} /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public {_quantity.Name}({_quantity.BaseType} value, {_unitEnumName} unit) + public {_quantity.Name}({_quantity.ValueType} value, {_unitEnumName} unit) {{ _value = value; _unit = unit; @@ -83,17 +83,17 @@ public struct {_quantity.Name} /// "); // Non decimal - Writer.WLCondition(_quantity.BaseType != "decimal", $@" - public static {_quantity.Name} MaxValue {{ get; }} = new {_quantity.Name}({_quantity.BaseType}.MaxValue, BaseUnit); + Writer.WLCondition(_quantity.ValueType != "decimal", $@" + public static {_quantity.Name} MaxValue {{ get; }} = new {_quantity.Name}({_quantity.ValueType}.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Duration /// - public static {_quantity.Name} MinValue {{ get; }} = new {_quantity.Name}({_quantity.BaseType}.MinValue, BaseUnit); + public static {_quantity.Name} MinValue {{ get; }} = new {_quantity.Name}({_quantity.ValueType}.MinValue, BaseUnit); "); // Decimal MaxValue = 79228162514264337593543950335M - Writer.WLCondition(_quantity.BaseType == "decimal", $@" + Writer.WLCondition(_quantity.ValueType == "decimal", $@" public static {_quantity.Name} MaxValue {{ get; }} = new {_quantity.Name}(79228162514264337593543950335M, BaseUnit); /// @@ -136,7 +136,7 @@ private void GenerateConversionProperties() /// "); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public {_quantity.BaseType} {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); + public {_quantity.ValueType} {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); "); } @@ -164,7 +164,7 @@ private void GenerateStaticFactoryMethods() /// If value is NaN or Infinity."); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public static {_quantity.Name} From{unit.PluralName}({_quantity.BaseType} {valueParamName}) => new {_quantity.Name}({valueParamName}, {_unitEnumName}.{unit.SingularName}); + public static {_quantity.Name} From{unit.PluralName}({_quantity.ValueType} {valueParamName}) => new {_quantity.Name}({valueParamName}, {_unitEnumName}.{unit.SingularName}); "); } @@ -175,7 +175,7 @@ private void GenerateStaticFactoryMethods() /// Value to convert from. /// Unit to convert from. /// {_quantity.Name} unit value. - public static {_quantity.Name} From({_quantity.BaseType} value, {_unitEnumName} fromUnit) + public static {_quantity.Name} From({_quantity.ValueType} value, {_unitEnumName} fromUnit) {{ return new {_quantity.Name}(value, fromUnit); }} @@ -187,67 +187,67 @@ private void GenerateStaticFactoryMethods() private void GenerateConversionMethods() { Writer.WL($@" - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public {_quantity.BaseType} As({_unitEnumName} unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public {_quantity.Name} ToUnit({_unitEnumName} unit) - {{ - var convertedValue = GetValueAs(unit); - return new {_quantity.Name}(convertedValue, unit); - }} - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private {_quantity.BaseType} GetValueInBaseUnit() - {{ - return Unit switch - {{"); + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public {_quantity.ValueType} As({_unitEnumName} unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public {_quantity.Name} ToUnit({_unitEnumName} unit) + {{ + var convertedValue = GetValueAs(unit); + return new {_quantity.Name}(convertedValue, unit); + }} + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private {_quantity.ValueType} GetValueInBaseUnit() + {{ + return Unit switch + {{"); foreach (var unit in _quantity.Units) { var func = unit.FromUnitToBaseFunc.Replace("{x}", "_value"); Writer.WL($@" - {_unitEnumName}.{unit.SingularName} => {func},"); + {_unitEnumName}.{unit.SingularName} => {func},"); } Writer.WL($@" - _ => throw new NotImplementedException($""Can not convert {{Unit}} to base units."") - }}; - }} + _ => throw new NotImplementedException($""Can not convert {{Unit}} to base units."") + }}; + }} - private {_quantity.BaseType} GetValueAs({_unitEnumName} unit) - {{ - if (Unit == unit) - return _value; + private {_quantity.ValueType} GetValueAs({_unitEnumName} unit) + {{ + if (Unit == unit) + return _value; - var baseUnitValue = GetValueInBaseUnit(); + var baseUnitValue = GetValueInBaseUnit(); - return unit switch - {{"); + return unit switch + {{"); foreach (var unit in _quantity.Units) { var func = unit.FromBaseToUnitFunc.Replace("{x}", "baseUnitValue"); Writer.WL($@" - {_unitEnumName}.{unit.SingularName} => {func},"); + {_unitEnumName}.{unit.SingularName} => {func},"); } Writer.WL(@" - _ => throw new NotImplementedException($""Can not convert {Unit} to {unit}."") - }; - } + _ => throw new NotImplementedException($""Can not convert {Unit} to {unit}."") + }; + } - #endregion"); + #endregion"); } /// @@ -263,5 +263,6 @@ private void GenerateConversionMethods() private static string? GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) ? null : $"[Obsolete(\"{obsoleteText}\")]"; + } } diff --git a/CodeGen/Generators/NanoFrameworkGen/SolutionGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/SolutionGenerator.cs index 8f30f4cb94..1b8384288d 100644 --- a/CodeGen/Generators/NanoFrameworkGen/SolutionGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/SolutionGenerator.cs @@ -15,7 +15,7 @@ public SolutionGenerator(Quantity[] quantities) _quantities = quantities; } - public override string Generate() + public string Generate() { StringBuilder sb = new(); Writer.WL($@"Microsoft Visual Studio Solution File, Format Version 12.00 diff --git a/CodeGen/Generators/NanoFrameworkGen/UnitTypeGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/UnitTypeGenerator.cs index 87fa652196..8868c83f88 100644 --- a/CodeGen/Generators/NanoFrameworkGen/UnitTypeGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/UnitTypeGenerator.cs @@ -3,7 +3,6 @@ using CodeGen.JsonTypes; namespace CodeGen.Generators.NanoFrameworkGen - { internal class UnitTypeGenerator : GeneratorBase { @@ -18,7 +17,7 @@ public UnitTypeGenerator(Quantity quantity, UnitEnumNameToValue unitEnumNameToVa _unitEnumName = $"{quantity.Name}Unit"; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL($@" @@ -29,9 +28,7 @@ namespace UnitsNet.Units #pragma warning disable 1591 public enum {_unitEnumName} - {{ - Undefined = 0,"); - + {{"); foreach (var unit in _quantity.Units) { if (unit.XmlDocSummary.HasText()) diff --git a/CodeGen/Generators/NanoFrameworkGenerator.cs b/CodeGen/Generators/NanoFrameworkGenerator.cs index cea788f0e2..4e0b6b8070 100644 --- a/CodeGen/Generators/NanoFrameworkGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGenerator.cs @@ -64,7 +64,7 @@ public static void Generate(string rootDir, Quantity[] quantities, QuantityNameT var lengthNuspecFile = Path.Combine(outputDir, "Length", "UnitsNet.NanoFramework.Length.nuspec"); var projectVersion = ParseVersion(File.ReadAllText(lengthNuspecFile), - new Regex(@"(?[\d\.]+)", RegexOptions.IgnoreCase), + new Regex(@"(?[\d.]+)(?-[a-z\d]+)?<\/version>", RegexOptions.IgnoreCase), "projectVersion"); foreach (var quantity in quantities) @@ -91,7 +91,7 @@ public static void Generate(string rootDir, Quantity[] quantities, QuantityNameT GenerateProject(quantity, Path.Combine(projectPath, $"{quantity.Name}.nfproj"), versions); // Convert decimal based units to floats; decimals are not supported by nanoFramework - if (quantity.BaseType == "decimal") + if (quantity.ValueType == "decimal") { var replacements = new Dictionary { @@ -396,8 +396,7 @@ private static string GeneratePackageConfigFile( "); - - if (NanoFrameworkGenerator.ProjectsRequiringMath.Contains(quantityName)) + if (ProjectsRequiringMath.Contains(quantityName)) { writer.WL($@" "); diff --git a/CodeGen/Generators/QuantityJsonFilesParser.cs b/CodeGen/Generators/QuantityJsonFilesParser.cs index 7b004de08c..945a9c66b0 100644 --- a/CodeGen/Generators/QuantityJsonFilesParser.cs +++ b/CodeGen/Generators/QuantityJsonFilesParser.cs @@ -15,7 +15,7 @@ namespace CodeGen.Generators /// /// Parses JSON files that define quantities and their units. /// This will later be used to generate source code and can be reused for different targets such as .NET framework, - /// WindowsRuntimeComponent and even other programming languages. + /// .NET Core, .NET nanoFramework and even other programming languages. /// internal static class QuantityJsonFilesParser { @@ -68,7 +68,7 @@ private static void FixConversionFunctionsForDecimalValueTypes(Quantity quantity foreach (var u in quantity.Units) // Use decimal for internal calculations if base type is not double, such as for long or int. { - if (string.Equals(quantity.BaseType, "decimal", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(quantity.ValueType, "decimal", StringComparison.OrdinalIgnoreCase)) { // Change any double literals like "1024d" to decimal literals "1024m" u.FromUnitToBaseFunc = u.FromUnitToBaseFunc.Replace("d", "m"); diff --git a/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs index 6577988301..d331fc52c6 100644 --- a/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs @@ -18,7 +18,7 @@ public IQuantityTestClassGenerator(Quantity[] quantities) _quantities = quantities; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL($@" @@ -62,16 +62,6 @@ public void QuantityInfo_IsSameAsStaticInfoProperty() Writer.WL($@" }} - [Fact] - public void Type_EqualsStaticQuantityTypeProperty() - {{ - void Assertion(QuantityType expected, IQuantity quantity) => Assert.Equal(expected, quantity.Type); -"); - foreach (var quantity in _quantities) Writer.WL($@" - Assertion({quantity.Name}.QuantityType, {quantity.Name}.Zero);"); - Writer.WL($@" - }} - [Fact] public void Dimensions_IsSameAsStaticBaseDimensions() {{ diff --git a/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs b/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs index 2f60d23605..848a56cb55 100644 --- a/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs @@ -17,7 +17,7 @@ public NumberExtensionsGenerator(Quantity quantity) _quantityName = quantity.Name; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); diff --git a/CodeGen/Generators/UnitsNetGen/NumberExtensionsTestClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/NumberExtensionsTestClassGenerator.cs index 2b8f81b107..456557e3d9 100644 --- a/CodeGen/Generators/UnitsNetGen/NumberExtensionsTestClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/NumberExtensionsTestClassGenerator.cs @@ -16,8 +16,7 @@ public NumberExtensionsTestClassGenerator(Quantity quantity) _quantityName = quantity.Name; } - - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); @@ -51,7 +50,7 @@ public class NumberTo{_quantityName}ExtensionsTests return Writer.ToString(); } - private string? GetObsoleteAttributeOrNull(string obsoleteText) => + private static string? GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) ? null : $"[Obsolete(\"{obsoleteText}\")]"; diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index f8f6fef1fa..99f4f3f7ee 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -25,7 +25,7 @@ public QuantityGenerator(Quantity quantity) throw new ArgumentException($"No unit found with SingularName equal to BaseUnit [{_quantity.BaseUnit}]. This unit must be defined.", nameof(quantity)); - _valueType = quantity.BaseType; + _valueType = quantity.ValueType; _unitEnumName = $"{quantity.Name}Unit"; BaseDimensions baseDimensions = quantity.BaseDimensions; @@ -40,7 +40,7 @@ public QuantityGenerator(Quantity quantity) } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL(@" @@ -48,7 +48,6 @@ public override string Generate() using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -61,7 +60,7 @@ namespace UnitsNet Writer.WL($@" /// /// - /// {_quantity.XmlDoc} + /// {_quantity.XmlDocSummary} /// "); Writer.WLCondition(_quantity.XmlDocRemarks.HasText(), $@" @@ -73,19 +72,19 @@ namespace UnitsNet Writer.W(@$" [DataContract] public readonly partial struct {_quantity.Name} : IQuantity<{_unitEnumName}>, "); - if (_quantity.BaseType == "decimal") + if (_quantity.ValueType == "decimal") { Writer.W("IDecimalQuantity, "); } - Writer.WL($"IEquatable<{_quantity.Name}>, IComparable, IComparable<{_quantity.Name}>, IConvertible, IFormattable"); + Writer.WL($"IComparable, IComparable<{_quantity.Name}>, IConvertible, IFormattable"); Writer.WL($@" {{ /// /// The numeric value this quantity was constructed with. /// [DataMember(Name = ""Value"", Order = 0)] - private readonly {_quantity.BaseType} _value; + private readonly {_quantity.ValueType} _value; /// /// The unit this quantity was constructed with. @@ -125,10 +124,7 @@ private void GenerateStaticConstructor() Writer.WL($@" BaseUnit = {_unitEnumName}.{_quantity.BaseUnit}; - MaxValue = new {_quantity.Name}({_valueType}.MaxValue, BaseUnit); - MinValue = new {_quantity.Name}({_valueType}.MinValue, BaseUnit); - QuantityType = QuantityType.{_quantity.Name}; - Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().Except(new {_unitEnumName}[]{{ {_unitEnumName}.Undefined }}).ToArray(); + Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().ToArray(); Zero = new {_quantity.Name}(0, BaseUnit); Info = new QuantityInfo<{_unitEnumName}>(""{_quantity.Name}"", new UnitInfo<{_unitEnumName}>[] @@ -163,7 +159,7 @@ private void GenerateStaticConstructor() Writer.WL($@" }}, - BaseUnit, Zero, BaseDimensions, QuantityType.{_quantity.Name}); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -180,13 +176,9 @@ private void GenerateInstanceConstructors() /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. /// If value is NaN or Infinity. - public {_quantity.Name}({_quantity.BaseType} value, {_unitEnumName} unit) - {{ - if (unit == {_unitEnumName}.Undefined) - throw new ArgumentException(""The quantity can not be created with an undefined unit."", nameof(unit)); -"); - - Writer.WL(_quantity.BaseType == "double" + public {_quantity.Name}({_quantity.ValueType} value, {_unitEnumName} unit) + {{"); + Writer.WL(_quantity.ValueType == "double" ? @" _value = Guard.EnsureValidNumber(value, nameof(value));" : @" @@ -211,7 +203,7 @@ private void GenerateInstanceConstructors() var firstUnitInfo = unitInfos.FirstOrDefault(); "); - Writer.WL(_quantity.BaseType == "double" + Writer.WL(_quantity.ValueType == "double" ? @" _value = Guard.EnsureValidNumber(value, nameof(value));" : @" @@ -245,24 +237,6 @@ private void GenerateStaticProperties() /// public static {_unitEnumName} BaseUnit {{ get; }} - /// - /// Represents the largest possible value of {_quantity.Name} - /// - [Obsolete(""MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848."")] - public static {_quantity.Name} MaxValue {{ get; }} - - /// - /// Represents the smallest possible value of {_quantity.Name} - /// - [Obsolete(""MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848."")] - public static {_quantity.Name} MinValue {{ get; }} - - /// - /// The of this quantity. - /// - [Obsolete(""QuantityType will be removed in the future. Use the Info property instead."")] - public static QuantityType QuantityType {{ get; }} - /// /// All units of measurement for the {_quantity.Name} quantity. /// @@ -288,12 +262,12 @@ private void GenerateProperties() public {_valueType} Value => _value; "); - // Need to provide explicit interface implementation for decimal quantities like Information - if (_quantity.BaseType != "double") - Writer.WL(@" - double IQuantity.Value => (double) _value; + Writer.WL(@" + /// + QuantityValue IQuantity.Value => _value; "); - if (_quantity.BaseType == "decimal") + // Need to provide explicit interface implementation for decimal quantities like Information + if (_quantity.ValueType == "decimal") Writer.WL(@" /// decimal IDecimalQuantity.Value => _value; @@ -311,12 +285,6 @@ private void GenerateProperties() /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete(""QuantityType will be removed in the future. Use the Info property instead."")] - public QuantityType Type => QuantityType.{_quantity.Name}; - /// /// The of this quantity. /// @@ -338,11 +306,11 @@ private void GenerateConversionProperties() Writer.WL($@" /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// "); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public double {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); + public {_quantity.ValueType} {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); "); } @@ -431,7 +399,7 @@ public static string GetAbbreviation({_unitEnumName} unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation({_unitEnumName} unit, IFormatProvider? provider) {{ return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -537,7 +505,7 @@ private void GenerateStaticParseMethods() /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static {_quantity.Name} Parse(string str, IFormatProvider? provider) {{ return QuantityParser.Default.Parse<{_quantity.Name}, {_unitEnumName}>( @@ -568,7 +536,7 @@ public static bool TryParse(string? str, out {_quantity.Name} result) /// /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out {_quantity.Name} result) {{ return QuantityParser.Default.TryParse<{_quantity.Name}, {_unitEnumName}>( @@ -596,7 +564,7 @@ public static bool TryParse(string? str, IFormatProvider? provider, out {_quanti /// Parse a unit string. /// /// String to parse. Typically in the form: {{number}} {{unit}} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit(""m"", new CultureInfo(""en-US"")); /// @@ -622,7 +590,7 @@ public static bool TryParseUnit(string str, out {_unitEnumName} unit) /// /// Length.TryParseUnit(""m"", new CultureInfo(""en-US"")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out {_unitEnumName} unit) {{ return UnitParser.Default.TryParse<{_unitEnumName}>(str, provider, out unit); @@ -684,7 +652,7 @@ private void GenerateArithmeticOperators() }} /// Get ratio value from dividing by . - public static double operator /({_quantity.Name} left, {_quantity.Name} right) + public static {_quantity.ValueType} operator /({_quantity.Name} left, {_quantity.Name} right) {{ return left.{_baseUnit.PluralName} / right.{_baseUnit.PluralName}; }} @@ -784,20 +752,6 @@ private void GenerateEqualityAndComparison() return left.Value > right.ToUnit(left.Unit).Value; }} - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==({_quantity.Name} left, {_quantity.Name} right) - {{ - return left.Equals(right); - }} - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=({_quantity.Name} left, {_quantity.Name} right) - {{ - return !(left == right); - }} - /// public int CompareTo(object obj) {{ @@ -813,23 +767,6 @@ public int CompareTo({_quantity.Name} other) return _value.CompareTo(other.ToUnit(this.Unit).Value); }} - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - {{ - if (obj is null || !(obj is {_quantity.Name} obj{_quantity.Name})) - return false; - - return Equals(obj{_quantity.Name}); - }} - - /// - /// Consider using for safely comparing floating point values. - public bool Equals({_quantity.Name} other) - {{ - return _value.Equals(other.ToUnit(this.Unit).Value); - }} - /// /// /// Compare equality to another {_quantity.Name} within the given absolute or relative tolerance. @@ -870,13 +807,13 @@ public bool Equals({_quantity.Name} other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals({_quantity.Name} other, double tolerance, ComparisonType comparisonType) + 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.""); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + {_quantity.ValueType} thisValue = this.Value; + {_quantity.ValueType} otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); }} @@ -903,17 +840,30 @@ private void GenerateConversionMethods() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As({_unitEnumName} unit) + public {_quantity.ValueType} As({_unitEnumName} unit) {{ if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; }} +"); + + if (_quantity.ValueType == "decimal") + { + Writer.WL($@" + + double IQuantity<{_unitEnumName}>.As({_unitEnumName} unit) + {{ + return (double)As(unit); + }} +"); + } + + Writer.WL($@" /// - public double As(UnitSystem unitSystem) + public {_quantity.ValueType} As(UnitSystem unitSystem) {{ if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -926,14 +876,27 @@ public double As(UnitSystem unitSystem) return As(firstUnitInfo.Value); }} +"); + + if (_quantity.ValueType == "decimal") + { + Writer.WL($@" + /// + double IQuantity.As(UnitSystem unitSystem) + {{ + return (double)As(unitSystem); + }} +"); + } + Writer.WL($@" /// double IQuantity.As(Enum unit) {{ - if (!(unit is {_unitEnumName} unitAs{_unitEnumName})) + if (!(unit is {_unitEnumName} typedUnit)) throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); - return As(unitAs{_unitEnumName}); + return (double)As(typedUnit); }} /// @@ -1030,10 +993,10 @@ private bool TryToUnit({_quantity.Name}Unit unit, out {_quantity.Name}? converte /// IQuantity IQuantity.ToUnit(Enum unit) {{ - if (!(unit is {_unitEnumName} unitAs{_unitEnumName})) + 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(unitAs{_unitEnumName}, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); }} /// @@ -1082,63 +1045,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) {{ return ToString(""g"", provider); }} - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@""This method is deprecated and will be removed at a future release. Please use ToString(""""s2"""") or ToString(""""s2"""", provider) where 2 is an example of the number passed to significantDigitsAfterRadix."")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - {{ - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - }} - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: ""{{0:0.##}} {{1}} for value and unit abbreviation respectively."" - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(""This method is deprecated and will be removed at a future release. Please use string.Format()."")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - {{ - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - }} - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) {{ - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); }} /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) {{ @@ -1146,7 +1075,7 @@ public string ToString(string format, IFormatProvider? provider) }} #endregion -"); +" ); } private void GenerateIConvertibleMethods() @@ -1225,8 +1154,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof({_unitEnumName})) return Unit; - else if (conversionType == typeof(QuantityType)) - return {_quantity.Name}.QuantityType; else if (conversionType == typeof(QuantityInfo)) return {_quantity.Name}.Info; else if (conversionType == typeof(BaseDimensions)) @@ -1254,7 +1181,7 @@ ulong IConvertible.ToUInt64(IFormatProvider provider) } /// - internal static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); + private static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); /// internal static string? GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); diff --git a/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs deleted file mode 100644 index 624f319486..0000000000 --- a/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs +++ /dev/null @@ -1,47 +0,0 @@ -using CodeGen.JsonTypes; - -namespace CodeGen.Generators.UnitsNetGen -{ - internal class QuantityTypeGenerator : GeneratorBase - { - private readonly Quantity[] _quantities; - - public QuantityTypeGenerator(Quantity[] quantities) - { - _quantities = quantities; - } - - public override string Generate() - { - Writer.WL(GeneratedFileHeader); - Writer.WL(@" -// ReSharper disable once CheckNamespace - -using System; - -namespace UnitsNet -{ - /// - /// Lists all generated quantities with the same name as the quantity struct type, - /// such as Length, Mass, Force etc. - /// This is useful for populating options in the UI, such as creating a generic conversion - /// tool with inputValue, quantityName, fromUnit and toUnit selectors. - /// - [Obsolete(""QuantityType will be removed in the future. Use the QuantityInfo class instead."")] - public enum QuantityType - { -// Missing XML comment for public type or member -#pragma warning disable CS1591 - Undefined = 0,"); - foreach (var quantity in _quantities) - Writer.WL($@" - {quantity.Name},"); - Writer.WL(@" -// Missing XML comment for public type or member -#pragma warning restore CS1591 - } -}"); - return Writer.ToString(); - } - } -} diff --git a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs index 383c895dff..2d7af1ba4f 100644 --- a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs @@ -12,14 +12,12 @@ public StaticQuantityGenerator(Quantity[] quantities) _quantities = quantities; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL(@" using System; using System.Globalization; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; using UnitsNet.Units; using System.Collections.Generic; @@ -43,29 +41,6 @@ public static partial class Quantity Writer.WL(@" }; - /// - /// Dynamically constructs a quantity of the given with the value in the quantity's base units. - /// - /// The of the quantity to create. - /// The value to construct the quantity with. - /// The created quantity. - [Obsolete(""QuantityType will be removed. Use FromQuantityInfo(QuantityInfo, QuantityValue) instead."")] - public static IQuantity FromQuantityType(QuantityType quantityType, QuantityValue value) - { - return quantityType switch - {"); - foreach (var quantity in _quantities) - { - var quantityName = quantity.Name; - Writer.WL($@" - QuantityType.{quantityName} => {quantityName}.From(value, {quantityName}.BaseUnit),"); - } - - Writer.WL(@" - _ => throw new ArgumentException($""{quantityType} is not a supported quantity type."") - }; - } - /// /// Dynamically constructs a quantity of the given with the value in the quantity's base units. /// @@ -86,7 +61,7 @@ public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, QuantityValu Writer.WL(@" _ => throw new ArgumentException($""{quantityInfo.Name} is not a supported quantity."") }; - } + } /// /// Try to dynamically construct a quantity. @@ -122,7 +97,7 @@ public static bool TryFrom(QuantityValue value, Enum unit, out IQuantity? quanti /// /// Try to dynamically parse a quantity string representation. /// - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Type of quantity, such as . /// Quantity string representation, such as ""1.5 kg"". Must be compatible with given quantity type. /// The resulting quantity if successful, otherwise default. @@ -131,7 +106,7 @@ public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, { quantity = default(IQuantity); - if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) + if (!typeof(IQuantity).IsAssignableFrom(quantityType)) return false; var parser = QuantityParser.Default; @@ -148,7 +123,7 @@ public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, Writer.WL(@" _ => false }; - } + } internal static IEnumerable GetQuantityTypes() {"); diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index 3a3df00e3e..9202705190 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -54,7 +54,7 @@ public UnitTestBaseClassGenerator(Quantity quantity) _unitEnumName = $"{quantity.Name}Unit"; _baseUnitEnglishAbbreviation = GetEnglishAbbreviation(_baseUnit); _baseUnitFullName = $"{_unitEnumName}.{_baseUnit.SingularName}"; - _numberSuffix = quantity.BaseType == "decimal" ? "m" : ""; + _numberSuffix = quantity.ValueType == "decimal" ? "m" : ""; } private string GetUnitFullName(Unit unit) => $"{_unitEnumName}.{unit.SingularName}"; @@ -69,7 +69,7 @@ private static string GetEnglishAbbreviation(Unit unit) return string.IsNullOrEmpty(unitAbbreviation) ? "" : $" {unitAbbreviation}"; } - public override string Generate() + public string Generate() { var baseUnitVariableName = _baseUnit.SingularName.ToLowerInvariant(); @@ -102,7 +102,7 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase continue; Writer.WL($@" - protected abstract double {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); + protected abstract {_quantity.ValueType} {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); } Writer.WL(""); @@ -114,12 +114,12 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase continue; Writer.WL($@" - protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); + protected virtual {_quantity.ValueType} {unit.PluralName}Tolerance {{ get {{ return { (_quantity.ValueType == "decimal" ? "1e-9m" : "1e-5") }; }} }}"); } Writer.WL($@" // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor({_unitEnumName} unit) + protected ({_quantity.ValueType} UnitsInBaseUnit, {_quantity.ValueType} Tolerence) GetConversionFactor({_unitEnumName} unit) {{ return unit switch {{"); @@ -140,25 +140,18 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase Writer.WL($@" }}; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - {{ - Assert.Throws(() => new {_quantity.Name}(({_quantity.BaseType})0.0, {_unitEnumName}.Undefined)); - }} - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() {{ var quantity = new {_quantity.Name}(); Assert.Equal(0, quantity.Value);"); - if (_quantity.BaseType == "decimal") Writer.WL($@" + if (_quantity.ValueType == "decimal") Writer.WL($@" Assert.Equal(0m, ((IDecimalQuantity)quantity).Value);"); Writer.WL($@" Assert.Equal({_baseUnitFullName}, quantity.Unit); }} - "); - if (_quantity.BaseType == "double") Writer.WL($@" + if (_quantity.ValueType == "double") Writer.WL($@" [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() {{ @@ -203,14 +196,9 @@ public void Ctor_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported() Assert.Equal({_quantity.Name}.Zero, quantityInfo.Zero); Assert.Equal(""{_quantity.Name}"", quantityInfo.Name); - Assert.Equal(QuantityType.{_quantity.Name}, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues<{_unitEnumName}>().Except(new[] {{{_unitEnumName}.Undefined}}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues<{_unitEnumName}>().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); }} [Fact] @@ -240,7 +228,7 @@ public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() Writer.WL($@" }} "); - if (_quantity.BaseType == "double") Writer.WL($@" + if (_quantity.ValueType == "double") Writer.WL($@" [Fact] public void From{_baseUnit.PluralName}_WithInfinityValue_ThrowsArgumentException() {{ @@ -367,7 +355,7 @@ public void ToUnit({_unitEnumName} unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); }} @@ -384,12 +372,8 @@ public void ToUnit_WithSameUnits_AreEqual({_unitEnumName} unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit({_unitEnumName} unit) {{ - // See if there is a unit available that is not the base unit. - var fromUnit = {_quantity.Name}.Units.FirstOrDefault(u => u != {_quantity.Name}.BaseUnit && u != {_unitEnumName}.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == {_unitEnumName}.Undefined) - fromUnit = {_quantity.Name}.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = {_quantity.Name}.Units.Where(u => u != {_quantity.Name}.BaseUnit).DefaultIfEmpty({_quantity.Name}.BaseUnit).FirstOrDefault(); var quantity = {_quantity.Name}.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -499,49 +483,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => {baseUnitVariableName}.CompareTo(null)); }} - [Fact] - public void EqualityOperators() - {{ - var a = {_quantity.Name}.From{_baseUnit.PluralName}(1); - var b = {_quantity.Name}.From{_baseUnit.PluralName}(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - }} - - [Fact] - public void Equals_SameType_IsImplemented() - {{ - var a = {_quantity.Name}.From{_baseUnit.PluralName}(1); - var b = {_quantity.Name}.From{_baseUnit.PluralName}(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - }} - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - {{ - object a = {_quantity.Name}.From{_baseUnit.PluralName}(1); - object b = {_quantity.Name}.From{_baseUnit.PluralName}(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - }} - [Fact] public void Equals_RelativeTolerance_IsImplemented() {{ @@ -571,21 +512,12 @@ public void EqualsReturnsFalseOnNull() Assert.False({baseUnitVariableName}.Equals(null)); }} - [Fact] - public void UnitsDoesNotContainUndefined() - {{ - Assert.DoesNotContain({_unitEnumName}.Undefined, {_quantity.Name}.Units); - }} - [Fact] public void HasAtLeastOneAbbreviationSpecified() {{ var units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>(); foreach(var unit in units) {{ - if (unit == {_unitEnumName}.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); }} }} @@ -599,8 +531,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() {{ - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(""en-US""); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(""en-US""); try {{"); foreach (var unit in _quantity.Units) { @@ -611,7 +543,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() }} finally {{ - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; }} }} @@ -632,10 +564,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() {{ - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try {{ - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal(""0.1{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s1"")); Assert.Equal(""0.12{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s2"")); Assert.Equal(""0.123{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s3"")); @@ -643,7 +575,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul }} finally {{ - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; }} }} @@ -657,29 +589,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal(""0.1235{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s4"", culture)); }} - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData(""en-US"")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) {{ var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - }} + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Throws(() => quantity.ToString(null, ""g"", null)); + Assert.Equal(quantity.ToString(""g"", formatProvider), quantity.ToString(null, formatProvider)); }} - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData(""g"")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) {{ var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, ""g""), quantity.ToString(null, ""g"")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); }} - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() {{ @@ -799,13 +730,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof({_unitEnumName}))); }} - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(QuantityType.{_quantity.Name}, Convert.ChangeType(quantity, typeof(QuantityType))); - }} - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() {{ diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs index 3580502e0b..e736652684 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs @@ -11,7 +11,7 @@ public UnitTestStubGenerator(Quantity quantity) _quantity = quantity; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL($@" diff --git a/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs index 0413e24fa3..97db24353b 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs @@ -17,7 +17,7 @@ public UnitTypeGenerator(Quantity quantity, UnitEnumNameToValue unitEnumNameToVa _unitEnumName = $"{quantity.Name}Unit"; } - public override string Generate() + public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL($@" @@ -28,9 +28,7 @@ namespace UnitsNet.Units #pragma warning disable 1591 public enum {_unitEnumName} - {{ - Undefined = 0,"); - + {{"); foreach (var unit in _quantity.Units) { if (unit.XmlDocSummary.HasText()) diff --git a/CodeGen/Generators/UnitsNetGenerator.cs b/CodeGen/Generators/UnitsNetGenerator.cs index 23d1ce6c99..4d75e68006 100644 --- a/CodeGen/Generators/UnitsNetGenerator.cs +++ b/CodeGen/Generators/UnitsNetGenerator.cs @@ -70,7 +70,6 @@ public static void Generate(string rootDir, Quantity[] quantities, QuantityNameT Log.Information(""); GenerateIQuantityTests(quantities, $"{testProjectDir}/GeneratedCode/IQuantityTests.g.cs"); - GenerateQuantityType(quantities, $"{outputDir}/QuantityType.g.cs"); GenerateStaticQuantity(quantities, $"{outputDir}/Quantity.g.cs"); var unitCount = quantities.SelectMany(q => q.Units).Count(); @@ -125,13 +124,6 @@ private static void GenerateIQuantityTests(Quantity[] quantities, string filePat Log.Information("✅ IQuantityTests.g.cs"); } - private static void GenerateQuantityType(Quantity[] quantities, string filePath) - { - var content = new QuantityTypeGenerator(quantities).Generate(); - File.WriteAllText(filePath, content); - Log.Information("✅ QuantityType.g.cs"); - } - private static void GenerateStaticQuantity(Quantity[] quantities, string filePath) { var content = new StaticQuantityGenerator(quantities).Generate(); diff --git a/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs deleted file mode 100644 index 1bc222cc76..0000000000 --- a/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs +++ /dev/null @@ -1,781 +0,0 @@ -// Licensed under MIT 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.UnitsNetWrcGen -{ - 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.BaseType; - _unitEnumName = $"{quantity.Name}Unit"; - - BaseDimensions baseDimensions = quantity.BaseDimensions; - _isDimensionless = baseDimensions == null || - baseDimensions.L == 0 && - baseDimensions.M == 0 && - baseDimensions.T == 0 && - baseDimensions.I == 0 && - baseDimensions.Θ == 0 && - baseDimensions.N == 0 && - baseDimensions.J == 0; - - } - - public override string Generate() - { - Writer.WL(GeneratedFileHeader); - Writer.WL(@" -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{"); - Writer.WL($@" - /// - /// {_quantity.XmlDoc} - /// "); - - Writer.WLCondition(_quantity.XmlDocRemarks.HasText(), $@" - /// - /// {_quantity.XmlDocRemarks} - /// "); - - Writer.WLIfText(1, GetObsoleteAttributeOrNull(_quantity)); - Writer.WL($@" - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class {_quantity.Name} : IQuantity - {{ - /// - /// The numeric value this quantity was constructed with. - /// - private readonly {_quantity.BaseType} _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly {_unitEnumName}? _unit; -"); - GenerateStaticConstructor(); - GenerateInstanceConstructors(); - GenerateStaticProperties(); - GenerateProperties(); - GenerateConversionProperties(); - GenerateStaticMethods(); - GenerateStaticFactoryMethods(); - GenerateStaticParseMethods(); - GenerateEqualityAndComparison(); - GenerateConversionMethods(); - GenerateToString(); - - Writer.WL($@" - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - {{ - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - }} - }} -}}"); - return Writer.ToString(); - } - - private void GenerateStaticConstructor() - { - var 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}; - MaxValue = new {_quantity.Name}({_valueType}.MaxValue, BaseUnit); - MinValue = new {_quantity.Name}({_valueType}.MinValue, BaseUnit); - QuantityType = QuantityType.{_quantity.Name}; - Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().Except(new {_unitEnumName}[]{{ {_unitEnumName}.Undefined }}).ToArray(); - Zero = new {_quantity.Name}(0, BaseUnit); - Info = new QuantityInfo(QuantityType.{_quantity.Name}, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - }} -"); - } - - private void GenerateInstanceConstructors() - { - Writer.WL($@" - /// - /// Creates the quantity with a value of 0 in the base unit {_baseUnit.SingularName}. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public {_quantity.Name}() - {{ - _value = 0; - _unit = BaseUnit; - }} - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private {_quantity.Name}({_quantity.BaseType} value, {_unitEnumName} unit) - {{ - if (unit == {_unitEnumName}.Undefined) - throw new ArgumentException(""The quantity can not be created with an undefined unit."", nameof(unit)); -"); - - Writer.WL(_quantity.BaseType == "double" - ? @" - _value = Guard.EnsureValidNumber(value, nameof(value));" - : @" - _value = value;"); - Writer.WL($@" - _unit = unit; - }} -"); - } - - private void GenerateStaticProperties() - { - Writer.WL($@" - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info {{ get; }} - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions {{ get; }} - - /// - /// The base unit of {_quantity.Name}, which is {_quantity.BaseUnit}. All conversions go via this value. - /// - public static {_unitEnumName} BaseUnit {{ get; }} - - /// - /// Represents the largest possible value of {_quantity.Name} - /// - public static {_quantity.Name} MaxValue {{ get; }} - - /// - /// Represents the smallest possible value of {_quantity.Name} - /// - public static {_quantity.Name} MinValue {{ get; }} - - /// - /// The of this quantity. - /// - [Obsolete(""QuantityType will be removed in the future. Use the Info property instead."")] - public static QuantityType QuantityType {{ get; }} - - /// - /// All units of measurement for the {_quantity.Name} quantity. - /// - public static {_unitEnumName}[] Units {{ get; }} - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit {_quantity.BaseUnit}. - /// - public static {_quantity.Name} Zero {{ get; }} - - #endregion -"); - } - - private void GenerateProperties() - { - Writer.WL($@" - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); -"); - - Writer.WL($@" - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public {_unitEnumName} Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete(""QuantityType will be removed in the future. Use the Info property instead."")] - public QuantityType Type => {_quantity.Name}.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => {_quantity.Name}.BaseDimensions; - - #endregion -"); - } - - private void GenerateConversionProperties() - { - Writer.WL(@" - #region Conversion Properties -"); - foreach (var unit in _quantity.Units) - { - if (unit.SkipConversionGeneration) - continue; - - Writer.WL($@" - /// - /// Gets a value of this quantity converted into - /// "); - Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); - Writer.WL($@" - public double {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); -"); - } - - Writer.WL(@" - - #endregion -"); - } - - private void GenerateStaticMethods() - { - Writer.WL($@" - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - {{"); - foreach(var unit in _quantity.Units) - { - foreach(var 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($@" - }} - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation({_unitEnumName} unit) - {{ - return GetAbbreviation(unit, null); - }} - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: ""en-US"") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation({_quantity.Name}Unit unit, [CanBeNull] string cultureName) - {{ - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - }} - - #endregion -"); - } - - private void GenerateStaticFactoryMethods() - { - Writer.WL(@" - #region Static Factory Methods -"); - foreach (var unit in _quantity.Units) - { - if (unit.SkipConversionGeneration) - continue; - - var valueParamName = unit.PluralName.ToLowerInvariant(); - Writer.WL($@" - /// - /// Creates a from . - /// - /// If value is NaN or Infinity."); - Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); - Writer.WL($@" - [Windows.Foundation.Metadata.DefaultOverload] - public static {_quantity.Name} From{unit.PluralName}(double {valueParamName}) - {{ - {_valueType} value = ({_valueType}) {valueParamName}; - return new {_quantity.Name}(value, {_unitEnumName}.{unit.SingularName}); - }} -"); - } - - Writer.WL($@" - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// {_quantity.Name} unit value. - // Fix name conflict with parameter ""value"" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName(""returnValue"")] - public static {_quantity.Name} From(double value, {_unitEnumName} fromUnit) - {{ - return new {_quantity.Name}(({_valueType})value, fromUnit); - }} - - #endregion -"); - } - - private void GenerateStaticParseMethods() - { - Writer.WL($@" - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format ""<quantity> <unit>"". - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// - /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// ""<quantity> <unit>"". Eg. ""5.5 m"" or ""1ft 2in"" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse(""1 cup"") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static {_quantity.Name} Parse(string str) - {{ - return Parse(str, null); - }} - - /// - /// Parse a string with one or two quantities of the format ""<quantity> <unit>"". - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// - /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// ""<quantity> <unit>"". Eg. ""5.5 m"" or ""1ft 2in"" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse(""1 cup"") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: ""en-US"") to use when parsing number and unit. Defaults to if null. - public static {_quantity.Name} Parse(string str, [CanBeNull] string cultureName) - {{ - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse<{_quantity.Name}, {_unitEnumName}>( - str, - provider, - From); - }} - - /// - /// Try to parse a string with one or two quantities of the format ""<quantity> <unit>"". - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// Resulting unit quantity if successful. - /// - /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); - /// - public static bool TryParse([CanBeNull] string str, out {_quantity.Name} result) - {{ - return TryParse(str, null, out result); - }} - - /// - /// Try to parse a string with one or two quantities of the format ""<quantity> <unit>"". - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); - /// - /// Name of culture (ex: ""en-US"") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out {_quantity.Name} result) - {{ - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse<{_quantity.Name}, {_unitEnumName}>( - str, - provider, - From, - out result); - }} - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// - /// Length.ParseUnit(""m"", new CultureInfo(""en-US"")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static {_unitEnumName} ParseUnit(string str) - {{ - return ParseUnit(str, null); - }} - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// - /// Length.ParseUnit(""m"", new CultureInfo(""en-US"")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: ""en-US"") to use when parsing number and unit. Defaults to if null. - public static {_unitEnumName} ParseUnit(string str, [CanBeNull] string cultureName) - {{ - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse<{_unitEnumName}>(str, provider); - }} - - public static bool TryParseUnit(string str, out {_unitEnumName} unit) - {{ - return TryParseUnit(str, null, out unit); - }} - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {{number}} {{unit}} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit(""m"", new CultureInfo(""en-US"")); - /// - /// Name of culture (ex: ""en-US"") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out {_unitEnumName} unit) - {{ - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse<{_unitEnumName}>(str, provider, out unit); - }} - - #endregion -"); - } - - private void GenerateEqualityAndComparison() - { - Writer.WL($@" - #region Equality / IComparable - - public int CompareTo(object obj) - {{ - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is {_quantity.Name} obj{_quantity.Name})) throw new ArgumentException(""Expected type {_quantity.Name}."", nameof(obj)); - - return CompareTo(obj{_quantity.Name}); - }} - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo({_quantity.Name} other) - {{ - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - }} - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - {{ - if (obj is null || !(obj is {_quantity.Name} obj{_quantity.Name})) - return false; - - return Equals(obj{_quantity.Name}); - }} - - public bool Equals({_quantity.Name} other) - {{ - return _value.Equals(other.AsBaseNumericType(this.Unit)); - }} - - /// - /// - /// Compare equality to another {_quantity.Name} within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals({_quantity.Name} other, double tolerance, ComparisonType comparisonType) - {{ - if (tolerance < 0) - throw new ArgumentOutOfRangeException(""tolerance"", ""Tolerance must be greater than or equal to 0.""); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - }} - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current {_quantity.Name}. - public override int GetHashCode() - {{ - return new {{ Info.Name, Value, Unit }}.GetHashCode(); - }} - - #endregion -"); - } - - private void GenerateConversionMethods() - { - Writer.WL($@" - #region Conversion Methods - - double IQuantity.As(object unit) => As(({_quantity.Name}Unit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As({_unitEnumName} unit) - {{ - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - }} - - /// - /// Converts this {_quantity.Name} to another {_quantity.Name} with the unit representation . - /// - /// A {_quantity.Name} with the specified unit. - public {_quantity.Name} ToUnit({_unitEnumName} unit) - {{ - var convertedValue = AsBaseNumericType(unit); - return new {_quantity.Name}(convertedValue, unit); - }} - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private {_valueType} AsBaseUnit() - {{ - switch(Unit) - {{"); - foreach (var unit in _quantity.Units) - { - var func = unit.FromUnitToBaseFunc.Replace("{x}", "_value"); - Writer.WL($@" - case {_unitEnumName}.{unit.SingularName}: return {func};"); - } - - Writer.WL($@" - default: - throw new NotImplementedException($""Can not convert {{Unit}} to base units.""); - }} - }} - - private {_valueType} AsBaseNumericType({_unitEnumName} unit) - {{ - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - {{"); - foreach (var unit in _quantity.Units) - { - var func = unit.FromBaseToUnitFunc.Replace("{x}", "baseUnitValue"); - Writer.WL($@" - case {_unitEnumName}.{unit.SingularName}: return {func};"); - } - - Writer.WL(@" - default: - throw new NotImplementedException($""Can not convert {Unit} to {unit}.""); - } - } - - #endregion -"); - } - - private void GenerateToString() - { - Writer.WL($@" - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - {{ - return ToString(null); - }} - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - {{ - var provider = cultureName; - return ToString(provider, 2); - }} - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - {{ - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - }} - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: ""{{0:0.##}} {{1}} for value and unit abbreviation respectively."" - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - {{ - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - }} - - #endregion -"); - } - - /// - internal static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); - - /// - internal static string? GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); - - /// - /// 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 - /// - private static string? GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) - ? null - : $"[Obsolete(\"{obsoleteText}\")]"; - } -} diff --git a/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs deleted file mode 100644 index e498d2d2d7..0000000000 --- a/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs +++ /dev/null @@ -1,43 +0,0 @@ -using CodeGen.JsonTypes; - -namespace CodeGen.Generators.UnitsNetWrcGen -{ - internal class QuantityTypeGenerator : GeneratorBase - { - private readonly Quantity[] _quantities; - - public QuantityTypeGenerator(Quantity[] quantities) - { - _quantities = quantities; - } - - public override string Generate() - { - Writer.WL(GeneratedFileHeader); - Writer.WL(@" -// ReSharper disable once CheckNamespace - -using System; - -namespace UnitsNet -{ - /// - /// Lists all generated quantities with the same name as the quantity struct type, - /// such as Length, Mass, Force etc. - /// This is useful for populating options in the UI, such as creating a generic conversion - /// tool with inputValue, quantityName, fromUnit and toUnit selectors. - /// - [Obsolete(""QuantityType will be removed in the future. Use the QuantityInfo class instead."")] - public enum QuantityType - { - Undefined = 0,"); - foreach (var quantity in _quantities) - Writer.WL($@" - {quantity.Name},"); - Writer.WL(@" - } -}"); - return Writer.ToString(); - } - } -} diff --git a/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs deleted file mode 100644 index 6adc611ad4..0000000000 --- a/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs +++ /dev/null @@ -1,130 +0,0 @@ -using CodeGen.Helpers; -using CodeGen.JsonTypes; - -namespace CodeGen.Generators.UnitsNetWrcGen -{ - internal class StaticQuantityGenerator : GeneratorBase - { - private readonly Quantity[] _quantities; - - public StaticQuantityGenerator(Quantity[] quantities) - { - _quantities = quantities; - } - - public override string Generate() - { - Writer.WL(GeneratedFileHeader); - Writer.WL(@" -using System; -using System.Collections.Generic; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// Dynamically parse or construct quantities when types are only known at runtime. - /// - internal static partial class Quantity - { - /// - /// Try to dynamically construct a quantity. - /// - /// Numeric value. - /// Unit enum value. - /// The resulting quantity if successful, otherwise default. - /// True if successful with assigned the value, otherwise false. - internal static bool TryFrom(double value, Enum unit, out IQuantity quantity) - { - switch (unit) - {"); - foreach (var quantity in _quantities) - { - var quantityName = quantity.Name; - var unitTypeName = $"{quantityName}Unit"; - var unitValue = unitTypeName.ToCamelCase(); - Writer.WL($@" - case {unitTypeName} {unitValue}: - quantity = {quantityName}.From(value, {unitValue}); - return true;"); - } - - Writer.WL($@" - default: - {{ - quantity = default(IQuantity); - return false; - }} - }} - }} - - /// - internal static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); - - /// - /// Dynamically parse a quantity string representation. - /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as ""1.5 kg"". Must be compatible with given quantity type. - /// The parsed quantity. - /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. - internal static IQuantity Parse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString) - {{ - if (!typeof(IQuantity).Wrap().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}}.""); - }} - - /// - internal static bool TryParse(Type quantityType, string quantityString, out IQuantity quantity) => - TryParse(null, quantityType, quantityString, out quantity); - - /// - /// Try to dynamically parse a quantity string representation. - /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as ""1.5 kg"". Must be compatible with given quantity type. - /// The resulting quantity if successful, otherwise default. - /// The parsed quantity. - internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString, out IQuantity quantity) - {{ - quantity = default(IQuantity); - - if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) - return false; - - var parser = QuantityParser.Default; -"); - foreach (var quantity in _quantities) - { - Writer.WL($@" - if (quantityType == typeof({quantity.Name})) - return parser.TryParse<{quantity.Name}, {quantity.Name}Unit>(quantityString, formatProvider, {quantity.Name}.From, out quantity); -"); - } - - Writer.WL($@" - throw new ArgumentException( - $""Type {{quantityType}} is not a known quantity type. Did you pass in a third-party quantity type defined outside UnitsNet library?""); - }} - - internal static IEnumerable GetQuantityTypes() - {{"); - foreach (var quantity in _quantities) - Writer.WL($@" - yield return typeof({quantity.Name});"); - Writer.WL($@" - }} - }} -}}"); - return Writer.ToString(); - } - } -} diff --git a/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs deleted file mode 100644 index 81bdc798c4..0000000000 --- a/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs +++ /dev/null @@ -1,66 +0,0 @@ -using CodeGen.Helpers; -using CodeGen.JsonTypes; - -namespace CodeGen.Generators.UnitsNetWrcGen -{ - internal class UnitTypeGenerator : GeneratorBase - { - private readonly Quantity _quantity; - private readonly string _unitEnumName; - - public UnitTypeGenerator(Quantity quantity) - { - _quantity = quantity; - _unitEnumName = $"{quantity.Name}Unit"; - } - - public override 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} - {{ - Undefined = 0,"); - - foreach (var unit in _quantity.Units) - { - if (unit.XmlDocSummary.HasText()) - { - Writer.WL(); - Writer.WL($@" - /// - /// {unit.XmlDocSummary} - /// "); - } - - if (unit.XmlDocRemarks.HasText()) - { - Writer.WL($@" - /// {unit.XmlDocRemarks}"); - } - - Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit.ObsoleteText)); - Writer.WL($@" - {unit.SingularName},"); - } - - Writer.WL($@" - }} - - #pragma warning restore 1591 -}}"); - return Writer.ToString(); - } - - private string? GetObsoleteAttributeOrNull(string obsoleteText) => - string.IsNullOrWhiteSpace(obsoleteText) ? - null : - $"[System.Obsolete(\"{obsoleteText}\")]"; - } -} diff --git a/CodeGen/Generators/UnitsNetWrcGenerator.cs b/CodeGen/Generators/UnitsNetWrcGenerator.cs deleted file mode 100644 index 32094248e8..0000000000 --- a/CodeGen/Generators/UnitsNetWrcGenerator.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Licensed under MIT 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.UnitsNetWrcGen; -using CodeGen.JsonTypes; -using Serilog; - -namespace CodeGen.Generators -{ - /// - /// Code generator for UnitsNet.WindowsRuntimeComponent project. - /// - internal static class UnitsNetWrcGenerator - { - private const int AlignPad = 35; - - /// - /// Generate source code for UnitsNet project for the given parsed quantities. - /// Outputs files relative to the given root dir to these locations: - /// - /// - /// - /// UnitsNet.WindowsRuntimeComponent/GeneratedCode (quantity and unit types, Quantity, - /// UnitAbbreviationCache) - /// - /// - /// - /// - /// Path to repository root directory. - /// The parsed quantities. - /// - /// NOTE! WRC target is deprecated and no longer actively maintained and will receive no new features. - /// No tests are generated or run for WRC and the code generator scripts are only updated to work when JSON schema - /// changes. - /// - public static void Generate(string rootDir, Quantity[] quantities) - { - var outputDir = $"{rootDir}/UnitsNet.WindowsRuntimeComponent/GeneratedCode"; - - // Ensure output directories exist - Directory.CreateDirectory($"{outputDir}/Quantities"); - Directory.CreateDirectory($"{outputDir}/Units"); - - foreach (var quantity in quantities) - { - GenerateQuantity(quantity, $"{outputDir}/Quantities/{quantity.Name}.g.cs"); - GenerateUnitType(quantity, $"{outputDir}/Units/{quantity.Name}Unit.g.cs"); - Log.Information("✅ {Quantity} (WRC)", quantity.Name); - } - - Log.Information(""); - GenerateQuantityType(quantities, $"{outputDir}/QuantityType.g.cs"); - GenerateStaticQuantity(quantities, $"{outputDir}/Quantity.g.cs"); - - var unitCount = quantities.SelectMany(q => q.Units).Count(); - Log.Information(""); - Log.Information("Total of {UnitCount} units and {QuantityCount} quantities (Windows Runtime Component)", unitCount, quantities.Length); - Log.Information(""); - } - - private static void GenerateQuantity(Quantity quantity, string filePath) - { - var content = new QuantityGenerator(quantity).Generate(); - File.WriteAllText(filePath, content); - } - - private static void GenerateUnitType(Quantity quantity, string filePath) - { - var content = new UnitTypeGenerator(quantity).Generate(); - File.WriteAllText(filePath, content); - } - - private static void GenerateQuantityType(Quantity[] quantities, string filePath) - { - var content = new QuantityTypeGenerator(quantities).Generate(); - File.WriteAllText(filePath, content); - Log.Information("✅ QuantityType.g.cs (WRC)"); - } - - private static void GenerateStaticQuantity(Quantity[] quantities, string filePath) - { - var content = new StaticQuantityGenerator(quantities).Generate(); - File.WriteAllText(filePath, content); - Log.Information("✅ Quantity.g.cs (WRC)"); - } - } -} diff --git a/CodeGen/JsonTypes/Quantity.cs b/CodeGen/JsonTypes/Quantity.cs index 0888bf8464..7075bdfe6a 100644 --- a/CodeGen/JsonTypes/Quantity.cs +++ b/CodeGen/JsonTypes/Quantity.cs @@ -11,16 +11,16 @@ internal class Quantity // 0649 Field is never assigned to #pragma warning disable 0649 - public BaseDimensions BaseDimensions = new BaseDimensions(); // Default to empty - public string BaseType = "double"; // TODO Rename to ValueType - public string BaseUnit; // TODO Rename to DefaultUnit or IntermediateConversionUnit to avoid confusion with Unit.BaseUnits + public BaseDimensions BaseDimensions = new(); // Default to empty + public string ValueType = "double"; + public string BaseUnit; public bool GenerateArithmetic = true; public bool Logarithmic = false; public int LogarithmicScalingFactor = 1; public string Name; public Unit[] Units = Array.Empty(); public string XmlDocRemarks; - public string XmlDoc; // TODO Rename to XmlDocSummary + public string XmlDocSummary; public string ObsoleteText; // 0649 Field is never assigned to diff --git a/CodeGen/Program.cs b/CodeGen/Program.cs index 49bf6b6cbc..d5589d5d1d 100644 --- a/CodeGen/Program.cs +++ b/CodeGen/Program.cs @@ -10,7 +10,10 @@ namespace CodeGen { - internal class Program + /// + /// Code generator for Units.NET. + /// + public class Program { /// /// Code generator for Units.NET. @@ -20,20 +23,17 @@ internal class Program /// Quantity types (Length, Mass, ...) /// /// - /// UnitsNet.QuantityType enum type (QuantityType.Length, QuantityType.Mass, ...) + /// Unit enum types (LengthUnit, MassUnit, ...) /// /// - /// UnitsNet.Quantity type + /// UnitsNet.Quantity class. /// /// - /// UnitsNet.UnitAbbreviationsCache + /// UnitsNet.UnitAbbreviationsCache class. /// /// /// Test stubs for testing conversion functions of all units, to be fleshed out by a human later /// - /// - /// Unit enum types (LengthUnit, MassUnit, ...) - /// /// /// /// @@ -43,10 +43,9 @@ internal class Program /// /// Verbose output? Defaults to false. /// The repository root directory, defaults to searching parent directories for UnitsNet.sln. - /// Skip generate UnitsNet.WindowsRuntimeComponent? Defaults to false. /// Skip generate nanoFramework Units? Defaults to false /// Update nanoFramework nuget dependencies? Defaults to false. - public static int Main(bool verbose = false, DirectoryInfo? repositoryRoot = null, bool skipWrc = false, bool skipNanoFramework = false, bool updateNanoFrameworkDependencies = false) + public static int Main(bool verbose = false, DirectoryInfo? repositoryRoot = null, bool skipNanoFramework = false, bool updateNanoFrameworkDependencies = false) { Log.Logger = new LoggerConfiguration() .WriteTo @@ -72,11 +71,6 @@ public static int Main(bool verbose = false, DirectoryInfo? repositoryRoot = nul UnitsNetGenerator.Generate(rootDir, quantities, quantityNameToUnitEnumValues); - if (!skipWrc) - { - UnitsNetWrcGenerator.Generate(rootDir, quantities); - } - if (updateNanoFrameworkDependencies) { if (!NanoFrameworkGenerator.UpdateNanoFrameworkDependencies( diff --git a/Common/UnitDefinitions/Acceleration.json b/Common/UnitDefinitions/Acceleration.json index f2c7cc9cd4..8fc62f841e 100644 --- a/Common/UnitDefinitions/Acceleration.json +++ b/Common/UnitDefinitions/Acceleration.json @@ -1,7 +1,7 @@ { "Name": "Acceleration", "BaseUnit": "MeterPerSecondSquared", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 1, "T": -2 diff --git a/Common/UnitDefinitions/AmountOfSubstance.json b/Common/UnitDefinitions/AmountOfSubstance.json index 5e593ca311..2941e3ccb1 100644 --- a/Common/UnitDefinitions/AmountOfSubstance.json +++ b/Common/UnitDefinitions/AmountOfSubstance.json @@ -1,7 +1,7 @@ { "Name": "AmountOfSubstance", "BaseUnit": "Mole", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "N": 1 }, diff --git a/Common/UnitDefinitions/AmplitudeRatio.json b/Common/UnitDefinitions/AmplitudeRatio.json index 6ceb62ae29..0190799f4e 100644 --- a/Common/UnitDefinitions/AmplitudeRatio.json +++ b/Common/UnitDefinitions/AmplitudeRatio.json @@ -3,7 +3,7 @@ "BaseUnit": "DecibelVolt", "Logarithmic": "True", "LogarithmicScalingFactor": "2", - "XmlDoc": "The strength of a signal expressed in decibels (dB) relative to one volt RMS.", + "XmlDocSummary": "The strength of a signal expressed in decibels (dB) relative to one volt RMS.", "Units": [ { "SingularName": "DecibelVolt", diff --git a/Common/UnitDefinitions/Angle.json b/Common/UnitDefinitions/Angle.json index cbafa45b4c..1f7b908af1 100644 --- a/Common/UnitDefinitions/Angle.json +++ b/Common/UnitDefinitions/Angle.json @@ -1,7 +1,7 @@ { "Name": "Angle", "BaseUnit": "Degree", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "Units": [ { "SingularName": "Radian", diff --git a/Common/UnitDefinitions/ApparentEnergy.json b/Common/UnitDefinitions/ApparentEnergy.json index 76688e5530..f656a25c02 100644 --- a/Common/UnitDefinitions/ApparentEnergy.json +++ b/Common/UnitDefinitions/ApparentEnergy.json @@ -1,7 +1,7 @@ { "Name": "ApparentEnergy", "BaseUnit": "VoltampereHour", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/ApparentPower.json b/Common/UnitDefinitions/ApparentPower.json index 63e4b68fa2..2685557dbd 100644 --- a/Common/UnitDefinitions/ApparentPower.json +++ b/Common/UnitDefinitions/ApparentPower.json @@ -1,7 +1,7 @@ { "Name": "ApparentPower", "BaseUnit": "Voltampere", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/Area.json b/Common/UnitDefinitions/Area.json index caf61d8aa5..715a335631 100644 --- a/Common/UnitDefinitions/Area.json +++ b/Common/UnitDefinitions/Area.json @@ -1,7 +1,7 @@ { "Name": "Area", "BaseUnit": "SquareMeter", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "L": 2 }, diff --git a/Common/UnitDefinitions/AreaDensity.json b/Common/UnitDefinitions/AreaDensity.json index ea9bb6b817..4e66410de6 100644 --- a/Common/UnitDefinitions/AreaDensity.json +++ b/Common/UnitDefinitions/AreaDensity.json @@ -1,7 +1,7 @@ { "Name": "AreaDensity", "BaseUnit": "KilogramPerSquareMeter", - "XmlDoc": "The area density of a two-dimensional object is calculated as the mass per unit area. For paper this is also called grammage.", + "XmlDocSummary": "The area density of a two-dimensional object is calculated as the mass per unit area. For paper this is also called grammage.", "BaseDimensions": { "L": -2, "M": 1 diff --git a/Common/UnitDefinitions/AreaMomentOfInertia.json b/Common/UnitDefinitions/AreaMomentOfInertia.json index 2491ed7a66..29dd2f5530 100644 --- a/Common/UnitDefinitions/AreaMomentOfInertia.json +++ b/Common/UnitDefinitions/AreaMomentOfInertia.json @@ -1,7 +1,7 @@ { "Name": "AreaMomentOfInertia", "BaseUnit": "MeterToTheFourth", - "XmlDoc": "A geometric property of an area that reflects how its points are distributed with regard to an axis.", + "XmlDocSummary": "A geometric property of an area that reflects how its points are distributed with regard to an axis.", "BaseDimensions": { "L": 4 }, diff --git a/Common/UnitDefinitions/BitRate.json b/Common/UnitDefinitions/BitRate.json index c4bfa93e1d..8f2ccd1e37 100644 --- a/Common/UnitDefinitions/BitRate.json +++ b/Common/UnitDefinitions/BitRate.json @@ -1,8 +1,8 @@ { "Name": "BitRate", "BaseUnit": "BitPerSecond", - "BaseType": "decimal", - "XmlDoc": "In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time.", + "ValueType": "decimal", + "XmlDocSummary": "In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Bit_rate", "BaseDimensions": { "T": -1 }, "Units": [ diff --git a/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json b/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json index dd22729d6b..ff498144da 100644 --- a/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json +++ b/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json @@ -1,7 +1,7 @@ { "Name": "BrakeSpecificFuelConsumption", "BaseUnit": "KilogramPerJoule", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": -2, "T": 2 diff --git a/Common/UnitDefinitions/Capacitance.json b/Common/UnitDefinitions/Capacitance.json index e2fa5517e1..a7e88a5985 100644 --- a/Common/UnitDefinitions/Capacitance.json +++ b/Common/UnitDefinitions/Capacitance.json @@ -1,7 +1,7 @@ { "Name": "Capacitance", "BaseUnit": "Farad", - "XmlDoc": "Capacitance is the ability of a body to store an electric charge.", + "XmlDocSummary": "Capacitance is the ability of a body to store an electric charge.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Capacitance", "BaseDimensions": { "L": -2, diff --git a/Common/UnitDefinitions/CoefficientOfThermalExpansion.json b/Common/UnitDefinitions/CoefficientOfThermalExpansion.json index 917ebf95a5..4b7870556f 100644 --- a/Common/UnitDefinitions/CoefficientOfThermalExpansion.json +++ b/Common/UnitDefinitions/CoefficientOfThermalExpansion.json @@ -1,7 +1,7 @@ { "Name": "CoefficientOfThermalExpansion", "BaseUnit": "InverseKelvin", - "XmlDoc": "A unit that represents a fractional change in size in response to a change in temperature.", + "XmlDocSummary": "A unit that represents a fractional change in size in response to a change in temperature.", "BaseDimensions": { "Θ": -1 }, diff --git a/Common/UnitDefinitions/Density.json b/Common/UnitDefinitions/Density.json index a4ef7e9eb4..29551305fb 100644 --- a/Common/UnitDefinitions/Density.json +++ b/Common/UnitDefinitions/Density.json @@ -1,7 +1,7 @@ { "Name": "Density", "BaseUnit": "KilogramPerCubicMeter", - "XmlDoc": "The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume.", + "XmlDocSummary": "The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Density", "BaseDimensions": { "L": -3, diff --git a/Common/UnitDefinitions/Duration.json b/Common/UnitDefinitions/Duration.json index 04883c491b..e4ed17a08b 100644 --- a/Common/UnitDefinitions/Duration.json +++ b/Common/UnitDefinitions/Duration.json @@ -1,7 +1,7 @@ { "Name": "Duration", "BaseUnit": "Second", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "T": 1 }, diff --git a/Common/UnitDefinitions/DynamicViscosity.json b/Common/UnitDefinitions/DynamicViscosity.json index f830e868e3..d42da56383 100644 --- a/Common/UnitDefinitions/DynamicViscosity.json +++ b/Common/UnitDefinitions/DynamicViscosity.json @@ -1,7 +1,7 @@ { "Name": "DynamicViscosity", "BaseUnit": "NewtonSecondPerMeterSquared", - "XmlDoc": "The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds", + "XmlDocSummary": "The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity", "BaseDimensions": { "L": -1, diff --git a/Common/UnitDefinitions/ElectricAdmittance.json b/Common/UnitDefinitions/ElectricAdmittance.json index 4df1eace4f..4c75bbf0f1 100644 --- a/Common/UnitDefinitions/ElectricAdmittance.json +++ b/Common/UnitDefinitions/ElectricAdmittance.json @@ -1,7 +1,7 @@ { "Name": "ElectricAdmittance", "BaseUnit": "Siemens", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "L": -2, "M": -1, diff --git a/Common/UnitDefinitions/ElectricCharge.json b/Common/UnitDefinitions/ElectricCharge.json index b4590f7152..46b85596da 100644 --- a/Common/UnitDefinitions/ElectricCharge.json +++ b/Common/UnitDefinitions/ElectricCharge.json @@ -1,7 +1,7 @@ { "Name": "ElectricCharge", "BaseUnit": "Coulomb", - "XmlDoc": "Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field.", + "XmlDocSummary": "Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electric_charge", "BaseDimensions": { "T": 1, diff --git a/Common/UnitDefinitions/ElectricChargeDensity.json b/Common/UnitDefinitions/ElectricChargeDensity.json index 23a4823a53..ce36e8b19d 100644 --- a/Common/UnitDefinitions/ElectricChargeDensity.json +++ b/Common/UnitDefinitions/ElectricChargeDensity.json @@ -1,7 +1,7 @@ { "Name": "ElectricChargeDensity", "BaseUnit": "CoulombPerCubicMeter", - "XmlDoc": "In electromagnetism, charge density is a measure of the amount of electric charge per volume.", + "XmlDocSummary": "In electromagnetism, charge density is a measure of the amount of electric charge per volume.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Charge_density", "BaseDimensions": { "L": -3, diff --git a/Common/UnitDefinitions/ElectricConductance.json b/Common/UnitDefinitions/ElectricConductance.json index 005c3c0413..334b6eaa64 100644 --- a/Common/UnitDefinitions/ElectricConductance.json +++ b/Common/UnitDefinitions/ElectricConductance.json @@ -1,7 +1,7 @@ { "Name": "ElectricConductance", "BaseUnit": "Siemens", - "XmlDoc": "The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor.", + "XmlDocSummary": "The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance", "BaseDimensions": { "L": -2, diff --git a/Common/UnitDefinitions/ElectricConductivity.json b/Common/UnitDefinitions/ElectricConductivity.json index e3ddd434a1..2bd4a0033b 100644 --- a/Common/UnitDefinitions/ElectricConductivity.json +++ b/Common/UnitDefinitions/ElectricConductivity.json @@ -1,7 +1,7 @@ { "Name": "ElectricConductivity", "BaseUnit": "SiemensPerMeter", - "XmlDoc": "Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current.", + "XmlDocSummary": "Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity", "BaseDimensions": { "L": -3, diff --git a/Common/UnitDefinitions/ElectricCurrent.json b/Common/UnitDefinitions/ElectricCurrent.json index 8b455d9062..6eba323536 100644 --- a/Common/UnitDefinitions/ElectricCurrent.json +++ b/Common/UnitDefinitions/ElectricCurrent.json @@ -1,7 +1,7 @@ { "Name": "ElectricCurrent", "BaseUnit": "Ampere", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "I": 1 }, diff --git a/Common/UnitDefinitions/ElectricCurrentDensity.json b/Common/UnitDefinitions/ElectricCurrentDensity.json index 314134ab94..d59571b095 100644 --- a/Common/UnitDefinitions/ElectricCurrentDensity.json +++ b/Common/UnitDefinitions/ElectricCurrentDensity.json @@ -1,7 +1,7 @@ { "Name": "ElectricCurrentDensity", "BaseUnit": "AmperePerSquareMeter", - "XmlDoc": "In electromagnetism, current density is the electric current per unit area of cross section.", + "XmlDocSummary": "In electromagnetism, current density is the electric current per unit area of cross section.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Current_density", "BaseDimensions": { "L": -2, diff --git a/Common/UnitDefinitions/ElectricCurrentGradient.json b/Common/UnitDefinitions/ElectricCurrentGradient.json index a73c844c32..8a127e3097 100644 --- a/Common/UnitDefinitions/ElectricCurrentGradient.json +++ b/Common/UnitDefinitions/ElectricCurrentGradient.json @@ -1,7 +1,7 @@ { "Name": "ElectricCurrentGradient", "BaseUnit": "AmperePerSecond", - "XmlDoc": "In electromagnetism, the current gradient describes how the current changes in time.", + "XmlDocSummary": "In electromagnetism, the current gradient describes how the current changes in time.", "BaseDimensions": { "T": -1, "I": 1 diff --git a/Common/UnitDefinitions/ElectricField.json b/Common/UnitDefinitions/ElectricField.json index f9d3723ff7..6b6b534fe8 100644 --- a/Common/UnitDefinitions/ElectricField.json +++ b/Common/UnitDefinitions/ElectricField.json @@ -1,7 +1,7 @@ { "Name": "ElectricField", "BaseUnit": "VoltPerMeter", - "XmlDoc": "An electric field is a force field that surrounds electric charges that attracts or repels other electric charges.", + "XmlDocSummary": "An electric field is a force field that surrounds electric charges that attracts or repels other electric charges.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electric_field", "BaseDimensions": { "L": 1, diff --git a/Common/UnitDefinitions/ElectricInductance.json b/Common/UnitDefinitions/ElectricInductance.json index 531c7c4cab..cdf3fac8b7 100644 --- a/Common/UnitDefinitions/ElectricInductance.json +++ b/Common/UnitDefinitions/ElectricInductance.json @@ -1,7 +1,7 @@ { "Name": "ElectricInductance", "BaseUnit": "Henry", - "XmlDoc": "Inductance is a property of an electrical conductor which opposes a change in current.", + "XmlDocSummary": "Inductance is a property of an electrical conductor which opposes a change in current.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Inductance", "BaseDimensions": { "L": 2, diff --git a/Common/UnitDefinitions/ElectricPotential.json b/Common/UnitDefinitions/ElectricPotential.json index 2a0fbb6b66..8ab5779792 100644 --- a/Common/UnitDefinitions/ElectricPotential.json +++ b/Common/UnitDefinitions/ElectricPotential.json @@ -1,7 +1,7 @@ { "Name": "ElectricPotential", "BaseUnit": "Volt", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/ElectricPotentialAc.json b/Common/UnitDefinitions/ElectricPotentialAc.json index 2b1bdeefaa..4fd5eb435d 100644 --- a/Common/UnitDefinitions/ElectricPotentialAc.json +++ b/Common/UnitDefinitions/ElectricPotentialAc.json @@ -1,7 +1,7 @@ { "Name": "ElectricPotentialAc", "BaseUnit": "VoltAc", - "XmlDoc": "The Electric Potential of a system known to use Alternating Current.", + "XmlDocSummary": "The Electric Potential of a system known to use Alternating Current.", "Units": [ { "SingularName": "VoltAc", diff --git a/Common/UnitDefinitions/ElectricPotentialChangeRate.json b/Common/UnitDefinitions/ElectricPotentialChangeRate.json index e09386c8cc..ed81c5aa1d 100644 --- a/Common/UnitDefinitions/ElectricPotentialChangeRate.json +++ b/Common/UnitDefinitions/ElectricPotentialChangeRate.json @@ -1,7 +1,7 @@ { "Name": "ElectricPotentialChangeRate", "BaseUnit": "VoltPerSecond", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/ElectricPotentialDc.json b/Common/UnitDefinitions/ElectricPotentialDc.json index b305e49e7e..734ac8bf70 100644 --- a/Common/UnitDefinitions/ElectricPotentialDc.json +++ b/Common/UnitDefinitions/ElectricPotentialDc.json @@ -1,7 +1,7 @@ { "Name": "ElectricPotentialDc", "BaseUnit": "VoltDc", - "XmlDoc": "The Electric Potential of a system known to use Direct Current.", + "XmlDocSummary": "The Electric Potential of a system known to use Direct Current.", "Units": [ { "SingularName": "VoltDc", diff --git a/Common/UnitDefinitions/ElectricResistance.json b/Common/UnitDefinitions/ElectricResistance.json index 542d6490b2..d6f608fedf 100644 --- a/Common/UnitDefinitions/ElectricResistance.json +++ b/Common/UnitDefinitions/ElectricResistance.json @@ -1,7 +1,7 @@ { "Name": "ElectricResistance", "BaseUnit": "Ohm", - "XmlDoc": "The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.", + "XmlDocSummary": "The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/ElectricResistivity.json b/Common/UnitDefinitions/ElectricResistivity.json index fec041bf9c..66a90070fb 100644 --- a/Common/UnitDefinitions/ElectricResistivity.json +++ b/Common/UnitDefinitions/ElectricResistivity.json @@ -1,7 +1,7 @@ { "Name": "ElectricResistivity", "BaseUnit": "OhmMeter", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity", "BaseDimensions": { "L": 3, diff --git a/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json b/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json index ecb13e3335..471a6f828a 100644 --- a/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json +++ b/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json @@ -1,7 +1,7 @@ { "Name": "ElectricSurfaceChargeDensity", "BaseUnit": "CoulombPerSquareMeter", - "XmlDoc": "In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area.", + "XmlDocSummary": "In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Charge_density", "BaseDimensions": { "L": -2, diff --git a/Common/UnitDefinitions/Energy.json b/Common/UnitDefinitions/Energy.json index d914c9ba38..1da6c0e196 100644 --- a/Common/UnitDefinitions/Energy.json +++ b/Common/UnitDefinitions/Energy.json @@ -1,7 +1,7 @@ { "Name": "Energy", "BaseUnit": "Joule", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/Entropy.json b/Common/UnitDefinitions/Entropy.json index 543dc39c19..cf45d4be28 100644 --- a/Common/UnitDefinitions/Entropy.json +++ b/Common/UnitDefinitions/Entropy.json @@ -1,7 +1,7 @@ { "Name": "Entropy", "BaseUnit": "JoulePerKelvin", - "XmlDoc": "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", + "XmlDocSummary": "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", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/Force.json b/Common/UnitDefinitions/Force.json index ededc47082..2cf971e9f3 100644 --- a/Common/UnitDefinitions/Force.json +++ b/Common/UnitDefinitions/Force.json @@ -1,7 +1,7 @@ { "Name": "Force", "BaseUnit": "Newton", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 1, "M": 1, diff --git a/Common/UnitDefinitions/ForceChangeRate.json b/Common/UnitDefinitions/ForceChangeRate.json index 5ed12f9dea..08bb0d754f 100644 --- a/Common/UnitDefinitions/ForceChangeRate.json +++ b/Common/UnitDefinitions/ForceChangeRate.json @@ -1,7 +1,7 @@ { "Name": "ForceChangeRate", "BaseUnit": "NewtonPerSecond", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "L": 1, "M": 1, diff --git a/Common/UnitDefinitions/ForcePerLength.json b/Common/UnitDefinitions/ForcePerLength.json index fbe2cea10a..c5fdb2533a 100644 --- a/Common/UnitDefinitions/ForcePerLength.json +++ b/Common/UnitDefinitions/ForcePerLength.json @@ -1,7 +1,7 @@ { "Name": "ForcePerLength", "BaseUnit": "NewtonPerMeter", - "XmlDoc": "The magnitude of force per unit length.", + "XmlDocSummary": "The magnitude of force per unit length.", "BaseDimensions": { "M": 1, "T": -2 diff --git a/Common/UnitDefinitions/Frequency.json b/Common/UnitDefinitions/Frequency.json index 5957f6bcd4..400a4f7f87 100644 --- a/Common/UnitDefinitions/Frequency.json +++ b/Common/UnitDefinitions/Frequency.json @@ -1,7 +1,7 @@ { "Name": "Frequency", "BaseUnit": "Hertz", - "XmlDoc": "The number of occurrences of a repeating event per unit time.", + "XmlDocSummary": "The number of occurrences of a repeating event per unit time.", "BaseDimensions": { "T": -1 }, diff --git a/Common/UnitDefinitions/FuelEfficiency.json b/Common/UnitDefinitions/FuelEfficiency.json index 8a8b2f4339..d0a27ce366 100644 --- a/Common/UnitDefinitions/FuelEfficiency.json +++ b/Common/UnitDefinitions/FuelEfficiency.json @@ -1,7 +1,7 @@ { "Name": "FuelEfficiency", "BaseUnit": "LiterPer100Kilometers", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Fuel_efficiency", "Units": [{ "SingularName": "LiterPer100Kilometers", diff --git a/Common/UnitDefinitions/HeatFlux.json b/Common/UnitDefinitions/HeatFlux.json index 225b2b5de3..2fd41d7dc7 100644 --- a/Common/UnitDefinitions/HeatFlux.json +++ b/Common/UnitDefinitions/HeatFlux.json @@ -1,7 +1,7 @@ { "Name": "HeatFlux", "BaseUnit": "WattPerSquareMeter", - "XmlDoc": "Heat flux is the flow of energy per unit of area per unit of time", + "XmlDocSummary": "Heat flux is the flow of energy per unit of area per unit of time", "BaseDimensions": { "M": 1, "T": -3 diff --git a/Common/UnitDefinitions/HeatTransferCoefficient.json b/Common/UnitDefinitions/HeatTransferCoefficient.json index d84d879954..4e6e82abd1 100644 --- a/Common/UnitDefinitions/HeatTransferCoefficient.json +++ b/Common/UnitDefinitions/HeatTransferCoefficient.json @@ -1,7 +1,7 @@ { "Name": "HeatTransferCoefficient", "BaseUnit": "WattPerSquareMeterKelvin", - "XmlDoc": "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)", + "XmlDocSummary": "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)", "BaseDimensions": { "M": 1, "T": -3, diff --git a/Common/UnitDefinitions/Illuminance.json b/Common/UnitDefinitions/Illuminance.json index 6d05a654e6..2c8b07c52f 100644 --- a/Common/UnitDefinitions/Illuminance.json +++ b/Common/UnitDefinitions/Illuminance.json @@ -1,7 +1,7 @@ { "Name": "Illuminance", "BaseUnit": "Lux", - "XmlDoc": "In photometry, illuminance is the total luminous flux incident on a surface, per unit area.", + "XmlDocSummary": "In photometry, illuminance is the total luminous flux incident on a surface, per unit area.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Illuminance", "BaseDimensions": { "L": -2, diff --git a/Common/UnitDefinitions/Information.json b/Common/UnitDefinitions/Information.json index df10da2126..39cb9f0636 100644 --- a/Common/UnitDefinitions/Information.json +++ b/Common/UnitDefinitions/Information.json @@ -1,8 +1,8 @@ { "Name": "Information", "BaseUnit": "Bit", - "BaseType": "decimal", - "XmlDoc": "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.", + "ValueType": "decimal", + "XmlDocSummary": "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.", "Units": [ { "SingularName": "Byte", diff --git a/Common/UnitDefinitions/Irradiance.json b/Common/UnitDefinitions/Irradiance.json index e19a246d4e..6608bdfb98 100644 --- a/Common/UnitDefinitions/Irradiance.json +++ b/Common/UnitDefinitions/Irradiance.json @@ -1,7 +1,7 @@ { "Name": "Irradiance", "BaseUnit": "WattPerSquareMeter", - "XmlDoc": "Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface.", + "XmlDocSummary": "Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface.", "BaseDimensions": { "M": 1, "T": -3 diff --git a/Common/UnitDefinitions/Irradiation.json b/Common/UnitDefinitions/Irradiation.json index 78b478af2d..1097c6e3b4 100644 --- a/Common/UnitDefinitions/Irradiation.json +++ b/Common/UnitDefinitions/Irradiation.json @@ -1,7 +1,7 @@ { "Name": "Irradiation", "BaseUnit": "JoulePerSquareMeter", - "XmlDoc": "Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources.", + "XmlDocSummary": "Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Irradiation", "BaseDimensions": { "M": 1, diff --git a/Common/UnitDefinitions/KinematicViscosity.json b/Common/UnitDefinitions/KinematicViscosity.json index d4beec0c0f..5de0e4c458 100644 --- a/Common/UnitDefinitions/KinematicViscosity.json +++ b/Common/UnitDefinitions/KinematicViscosity.json @@ -1,7 +1,7 @@ { "Name": "KinematicViscosity", "BaseUnit": "SquareMeterPerSecond", - "XmlDoc": "The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress.", + "XmlDocSummary": "The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Viscosity", "BaseDimensions": { "L": 2, diff --git a/Common/UnitDefinitions/LapseRate.json b/Common/UnitDefinitions/LapseRate.json index 9cffb69e94..8f6d875506 100644 --- a/Common/UnitDefinitions/LapseRate.json +++ b/Common/UnitDefinitions/LapseRate.json @@ -1,8 +1,8 @@ { "Name": "LapseRate", "BaseUnit": "DegreeCelsiusPerKilometer", + "XmlDocSummary": "Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.", "ObsoleteText": "Use TemperatureGradient instead.", - "XmlDoc": "Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.", "BaseDimensions": { "L": -1, "Θ": 1 diff --git a/Common/UnitDefinitions/Length.json b/Common/UnitDefinitions/Length.json index 96ebf360ff..73c77d5873 100644 --- a/Common/UnitDefinitions/Length.json +++ b/Common/UnitDefinitions/Length.json @@ -1,7 +1,7 @@ { "Name": "Length", "BaseUnit": "Meter", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 1 }, diff --git a/Common/UnitDefinitions/Level.json b/Common/UnitDefinitions/Level.json index 32cc692242..aa69df4f1f 100644 --- a/Common/UnitDefinitions/Level.json +++ b/Common/UnitDefinitions/Level.json @@ -3,7 +3,7 @@ "BaseUnit": "Decibel", "Logarithmic": "True", "LogarithmicScalingFactor": "1", - "XmlDoc": "Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units.", + "XmlDocSummary": "Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units.", "Units": [ { "SingularName": "Decibel", diff --git a/Common/UnitDefinitions/LinearDensity.json b/Common/UnitDefinitions/LinearDensity.json index e236005461..ac64bafda7 100644 --- a/Common/UnitDefinitions/LinearDensity.json +++ b/Common/UnitDefinitions/LinearDensity.json @@ -1,7 +1,7 @@ { "Name": "LinearDensity", "BaseUnit": "KilogramPerMeter", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Linear_density", "BaseDimensions": { "L": -1, diff --git a/Common/UnitDefinitions/LinearPowerDensity.json b/Common/UnitDefinitions/LinearPowerDensity.json index 7aff1d4a93..2802ee7aa1 100644 --- a/Common/UnitDefinitions/LinearPowerDensity.json +++ b/Common/UnitDefinitions/LinearPowerDensity.json @@ -1,7 +1,7 @@ { "Name": "LinearPowerDensity", "BaseUnit": "WattPerMeter", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Linear_density", "BaseDimensions": { "M": 1, diff --git a/Common/UnitDefinitions/Luminosity.json b/Common/UnitDefinitions/Luminosity.json index a6e6512728..e0caa0eab7 100644 --- a/Common/UnitDefinitions/Luminosity.json +++ b/Common/UnitDefinitions/Luminosity.json @@ -1,8 +1,7 @@ { "Name": "Luminosity", "BaseUnit": "Watt", - "BaseType": "double", - "XmlDoc": "Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object.", + "XmlDocSummary": "Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminosity", "BaseDimensions": { "L": 2, diff --git a/Common/UnitDefinitions/LuminousFlux.json b/Common/UnitDefinitions/LuminousFlux.json index af9e070a27..844a6f2b69 100644 --- a/Common/UnitDefinitions/LuminousFlux.json +++ b/Common/UnitDefinitions/LuminousFlux.json @@ -1,7 +1,7 @@ { "Name": "LuminousFlux", "BaseUnit": "Lumen", - "XmlDoc": "In photometry, luminous flux or luminous power is the measure of the perceived power of light.", + "XmlDocSummary": "In photometry, luminous flux or luminous power is the measure of the perceived power of light.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminous_flux", "BaseDimensions": { "J": 1 diff --git a/Common/UnitDefinitions/LuminousIntensity.json b/Common/UnitDefinitions/LuminousIntensity.json index c7cd0f0241..c363940d11 100644 --- a/Common/UnitDefinitions/LuminousIntensity.json +++ b/Common/UnitDefinitions/LuminousIntensity.json @@ -1,7 +1,7 @@ { "Name": "LuminousIntensity", "BaseUnit": "Candela", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminous_intensity", "BaseDimensions": { "J": 1 diff --git a/Common/UnitDefinitions/MagneticField.json b/Common/UnitDefinitions/MagneticField.json index 5df8a20f58..4f356e2650 100644 --- a/Common/UnitDefinitions/MagneticField.json +++ b/Common/UnitDefinitions/MagneticField.json @@ -1,7 +1,7 @@ { "Name": "MagneticField", "BaseUnit": "Tesla", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetic_field", "BaseDimensions": { "M": 1, diff --git a/Common/UnitDefinitions/MagneticFlux.json b/Common/UnitDefinitions/MagneticFlux.json index 48c987fef3..5307d9fad3 100644 --- a/Common/UnitDefinitions/MagneticFlux.json +++ b/Common/UnitDefinitions/MagneticFlux.json @@ -1,7 +1,7 @@ { "Name": "MagneticFlux", "BaseUnit": "Weber", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetic_flux", "BaseDimensions": { "L": 2, diff --git a/Common/UnitDefinitions/Magnetization.json b/Common/UnitDefinitions/Magnetization.json index 2bfd605198..a8a6b5f6fb 100644 --- a/Common/UnitDefinitions/Magnetization.json +++ b/Common/UnitDefinitions/Magnetization.json @@ -1,7 +1,7 @@ { "Name": "Magnetization", "BaseUnit": "AmperePerMeter", - "XmlDoc": "In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material.", + "XmlDocSummary": "In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetization", "BaseDimensions": { "L": -1, diff --git a/Common/UnitDefinitions/Mass.json b/Common/UnitDefinitions/Mass.json index 7ca070cbcc..ce6e11a5fc 100644 --- a/Common/UnitDefinitions/Mass.json +++ b/Common/UnitDefinitions/Mass.json @@ -1,7 +1,7 @@ { "Name": "Mass", "BaseUnit": "Kilogram", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "M": 1 }, diff --git a/Common/UnitDefinitions/MassConcentration.json b/Common/UnitDefinitions/MassConcentration.json index 8d0b90bb3d..a8f7d6097c 100644 --- a/Common/UnitDefinitions/MassConcentration.json +++ b/Common/UnitDefinitions/MassConcentration.json @@ -1,7 +1,7 @@ { "Name": "MassConcentration", "BaseUnit": "KilogramPerCubicMeter", - "XmlDoc": "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", + "XmlDocSummary": "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", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Mass_concentration_(chemistry)", "BaseDimensions": { "M": 1, diff --git a/Common/UnitDefinitions/MassFlow.json b/Common/UnitDefinitions/MassFlow.json index 2701211983..509abd6a53 100644 --- a/Common/UnitDefinitions/MassFlow.json +++ b/Common/UnitDefinitions/MassFlow.json @@ -1,7 +1,7 @@ { "Name": "MassFlow", "BaseUnit": "GramPerSecond", - "XmlDoc": "Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time).", + "XmlDocSummary": "Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time).", "BaseDimensions": { "M": 1, "T": -1 diff --git a/Common/UnitDefinitions/MassFlux.json b/Common/UnitDefinitions/MassFlux.json index c96fbb6775..fe66af7430 100644 --- a/Common/UnitDefinitions/MassFlux.json +++ b/Common/UnitDefinitions/MassFlux.json @@ -1,7 +1,7 @@ { "Name": "MassFlux", "BaseUnit": "KilogramPerSecondPerSquareMeter", - "XmlDoc": "Mass flux is the mass flow rate per unit area.", + "XmlDocSummary": "Mass flux is the mass flow rate per unit area.", "BaseDimensions": { "L": -2, "M": 1, diff --git a/Common/UnitDefinitions/MassFraction.json b/Common/UnitDefinitions/MassFraction.json index 79e9cde701..1126615082 100644 --- a/Common/UnitDefinitions/MassFraction.json +++ b/Common/UnitDefinitions/MassFraction.json @@ -1,7 +1,7 @@ { "Name": "MassFraction", "BaseUnit": "DecimalFraction", - "XmlDoc": "The mass fraction is defined as the mass of a constituent divided by the total mass of the mixture.", + "XmlDocSummary": "The mass fraction is defined as the mass of a constituent divided by the total mass of the mixture.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Mass_fraction_(chemistry)", "Units": [ { diff --git a/Common/UnitDefinitions/MassMomentOfInertia.json b/Common/UnitDefinitions/MassMomentOfInertia.json index 0e278599d1..87f7a4ee11 100644 --- a/Common/UnitDefinitions/MassMomentOfInertia.json +++ b/Common/UnitDefinitions/MassMomentOfInertia.json @@ -1,7 +1,7 @@ { "Name": "MassMomentOfInertia", "BaseUnit": "KilogramSquareMeter", - "XmlDoc": "A property of body reflects how its mass is distributed with regard to an axis.", + "XmlDocSummary": "A property of body reflects how its mass is distributed with regard to an axis.", "BaseDimensions": { "L": 2, "M": 1 diff --git a/Common/UnitDefinitions/MolarEnergy.json b/Common/UnitDefinitions/MolarEnergy.json index d71f0d75d9..93add4f13e 100644 --- a/Common/UnitDefinitions/MolarEnergy.json +++ b/Common/UnitDefinitions/MolarEnergy.json @@ -1,7 +1,7 @@ { "Name": "MolarEnergy", "BaseUnit": "JoulePerMole", - "XmlDoc": "Molar energy is the amount of energy stored in 1 mole of a substance.", + "XmlDocSummary": "Molar energy is the amount of energy stored in 1 mole of a substance.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/MolarEntropy.json b/Common/UnitDefinitions/MolarEntropy.json index 701c21639c..53b6c96bd5 100644 --- a/Common/UnitDefinitions/MolarEntropy.json +++ b/Common/UnitDefinitions/MolarEntropy.json @@ -1,7 +1,7 @@ { "Name": "MolarEntropy", "BaseUnit": "JoulePerMoleKelvin", - "XmlDoc": "Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin.", + "XmlDocSummary": "Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/MolarMass.json b/Common/UnitDefinitions/MolarMass.json index 46404668e7..49c31aae60 100644 --- a/Common/UnitDefinitions/MolarMass.json +++ b/Common/UnitDefinitions/MolarMass.json @@ -1,7 +1,7 @@ { "Name": "MolarMass", "BaseUnit": "KilogramPerMole", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "M": 1, "N": -1 diff --git a/Common/UnitDefinitions/Molarity.json b/Common/UnitDefinitions/Molarity.json index c5b67fc2a6..73da85caf1 100644 --- a/Common/UnitDefinitions/Molarity.json +++ b/Common/UnitDefinitions/Molarity.json @@ -1,7 +1,7 @@ { "Name": "Molarity", "BaseUnit": "MolesPerCubicMeter", - "XmlDoc": "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. ", + "XmlDocSummary": "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. ", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Molar_concentration", "BaseDimensions": { "L": -3, diff --git a/Common/UnitDefinitions/Permeability.json b/Common/UnitDefinitions/Permeability.json index 111039cbb9..cb6c794fe4 100644 --- a/Common/UnitDefinitions/Permeability.json +++ b/Common/UnitDefinitions/Permeability.json @@ -1,7 +1,7 @@ { "Name": "Permeability", "BaseUnit": "HenryPerMeter", - "XmlDoc": "In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.", + "XmlDocSummary": "In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Permeability_(electromagnetism)", "BaseDimensions": { "L": 1, diff --git a/Common/UnitDefinitions/Permittivity.json b/Common/UnitDefinitions/Permittivity.json index f34db2eb89..ebdd6232f1 100644 --- a/Common/UnitDefinitions/Permittivity.json +++ b/Common/UnitDefinitions/Permittivity.json @@ -1,7 +1,7 @@ { "Name": "Permittivity", "BaseUnit": "FaradPerMeter", - "XmlDoc": "In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.", + "XmlDocSummary": "In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Permittivity", "BaseDimensions": { "L": -3, diff --git a/Common/UnitDefinitions/Power.json b/Common/UnitDefinitions/Power.json index a8b3a5c231..ce491fa507 100644 --- a/Common/UnitDefinitions/Power.json +++ b/Common/UnitDefinitions/Power.json @@ -1,8 +1,8 @@ { "Name": "Power", "BaseUnit": "Watt", - "BaseType": "decimal", - "XmlDoc": "In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time.", + "ValueType": "decimal", + "XmlDocSummary": "In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time.", "BaseDimensions": { "L": 2, "M": 1, @@ -85,8 +85,8 @@ { "SingularName": "BritishThermalUnitPerHour", "PluralName": "BritishThermalUnitsPerHour", - "FromUnitToBaseFunc": "{x} * 0.293071m", - "FromBaseToUnitFunc": "{x} / 0.293071m", + "FromUnitToBaseFunc": "{x} * 0.29307107017m", + "FromBaseToUnitFunc": "{x} / 0.29307107017m", "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { diff --git a/Common/UnitDefinitions/PowerDensity.json b/Common/UnitDefinitions/PowerDensity.json index 02a8ad350d..0318d9cd42 100644 --- a/Common/UnitDefinitions/PowerDensity.json +++ b/Common/UnitDefinitions/PowerDensity.json @@ -1,7 +1,7 @@ { "Name": "PowerDensity", "BaseUnit": "WattPerCubicMeter", - "XmlDoc": "The amount of power in a volume.", + "XmlDocSummary": "The amount of power in a volume.", "BaseDimensions": { "L": -1, "M": 1, diff --git a/Common/UnitDefinitions/PowerRatio.json b/Common/UnitDefinitions/PowerRatio.json index 84869fac2e..6a7df73a1d 100644 --- a/Common/UnitDefinitions/PowerRatio.json +++ b/Common/UnitDefinitions/PowerRatio.json @@ -3,7 +3,7 @@ "BaseUnit": "DecibelWatt", "Logarithmic": "True", "LogarithmicScalingFactor": "1", - "XmlDoc": "The strength of a signal expressed in decibels (dB) relative to one watt.", + "XmlDocSummary": "The strength of a signal expressed in decibels (dB) relative to one watt.", "Units": [ { "SingularName": "DecibelWatt", diff --git a/Common/UnitDefinitions/Pressure.json b/Common/UnitDefinitions/Pressure.json index 45ce2f9b61..89b22e4e3c 100644 --- a/Common/UnitDefinitions/Pressure.json +++ b/Common/UnitDefinitions/Pressure.json @@ -1,7 +1,7 @@ { "Name": "Pressure", "BaseUnit": "Pascal", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "L": -1, "M": 1, diff --git a/Common/UnitDefinitions/PressureChangeRate.json b/Common/UnitDefinitions/PressureChangeRate.json index 1f2ebc13e1..6f60ee8d25 100644 --- a/Common/UnitDefinitions/PressureChangeRate.json +++ b/Common/UnitDefinitions/PressureChangeRate.json @@ -1,7 +1,7 @@ { "Name": "PressureChangeRate", "BaseUnit": "PascalPerSecond", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "L": -1, "M": 1, diff --git a/Common/UnitDefinitions/Ratio.json b/Common/UnitDefinitions/Ratio.json index 28f17b038b..475c9e722b 100644 --- a/Common/UnitDefinitions/Ratio.json +++ b/Common/UnitDefinitions/Ratio.json @@ -1,7 +1,7 @@ { "Name": "Ratio", "BaseUnit": "DecimalFraction", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "Units": [ { "SingularName": "DecimalFraction", diff --git a/Common/UnitDefinitions/RatioChangeRate.json b/Common/UnitDefinitions/RatioChangeRate.json index b6625f39ca..be72a57bde 100644 --- a/Common/UnitDefinitions/RatioChangeRate.json +++ b/Common/UnitDefinitions/RatioChangeRate.json @@ -1,7 +1,7 @@ { "Name": "RatioChangeRate", "BaseUnit": "DecimalFractionPerSecond", - "XmlDoc": "The change in ratio per unit of time.", + "XmlDocSummary": "The change in ratio per unit of time.", "BaseDimensions": { "T": -1 }, "Units": [ { diff --git a/Common/UnitDefinitions/ReactiveEnergy.json b/Common/UnitDefinitions/ReactiveEnergy.json index 0c34565899..3180621fcf 100644 --- a/Common/UnitDefinitions/ReactiveEnergy.json +++ b/Common/UnitDefinitions/ReactiveEnergy.json @@ -1,7 +1,7 @@ { "Name": "ReactiveEnergy", "BaseUnit": "VoltampereReactiveHour", - "XmlDoc": "The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour.", + "XmlDocSummary": "The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/ReactivePower.json b/Common/UnitDefinitions/ReactivePower.json index 48d36a1099..51c981cc83 100644 --- a/Common/UnitDefinitions/ReactivePower.json +++ b/Common/UnitDefinitions/ReactivePower.json @@ -1,7 +1,7 @@ { "Name": "ReactivePower", "BaseUnit": "VoltampereReactive", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/ReciprocalArea.json b/Common/UnitDefinitions/ReciprocalArea.json index 21196fa6af..425302d1cd 100644 --- a/Common/UnitDefinitions/ReciprocalArea.json +++ b/Common/UnitDefinitions/ReciprocalArea.json @@ -1,7 +1,7 @@ { "Name": "ReciprocalArea", "BaseUnit": "InverseSquareMeter", - "XmlDoc": "Reciprocal area (Inverse-square) quantity is used to specify a physical quantity inversely proportional to the square of the distance.", + "XmlDocSummary": "Reciprocal area (Inverse-square) quantity is used to specify a physical quantity inversely proportional to the square of the distance.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Inverse-square_law", "BaseDimensions": { "L": -2 @@ -141,4 +141,3 @@ } ] } - \ No newline at end of file diff --git a/Common/UnitDefinitions/ReciprocalLength.json b/Common/UnitDefinitions/ReciprocalLength.json index f10373560f..adec3d17b2 100644 --- a/Common/UnitDefinitions/ReciprocalLength.json +++ b/Common/UnitDefinitions/ReciprocalLength.json @@ -1,7 +1,7 @@ { "Name": "ReciprocalLength", "BaseUnit": "InverseMeter", - "XmlDoc": "Reciprocal (Inverse) Length is used in various fields of science and mathematics. It is defined as the inverse value of a length unit.", + "XmlDocSummary": "Reciprocal (Inverse) Length is used in various fields of science and mathematics. It is defined as the inverse value of a length unit.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Reciprocal_length", "BaseDimensions": { "L": -1 diff --git a/Common/UnitDefinitions/RelativeHumidity.json b/Common/UnitDefinitions/RelativeHumidity.json index 57a5951359..93f317a9fe 100644 --- a/Common/UnitDefinitions/RelativeHumidity.json +++ b/Common/UnitDefinitions/RelativeHumidity.json @@ -1,7 +1,7 @@ { "Name": "RelativeHumidity", "BaseUnit": "Percent", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "Units": [ { "SingularName": "Percent", diff --git a/Common/UnitDefinitions/RotationalAcceleration.json b/Common/UnitDefinitions/RotationalAcceleration.json index 6bd3a2aeb0..90e7ce0879 100644 --- a/Common/UnitDefinitions/RotationalAcceleration.json +++ b/Common/UnitDefinitions/RotationalAcceleration.json @@ -1,7 +1,7 @@ { "Name": "RotationalAcceleration", "BaseUnit": "RadianPerSecondSquared", - "XmlDoc": "Angular acceleration is the rate of change of rotational speed.", + "XmlDocSummary": "Angular acceleration is the rate of change of rotational speed.", "BaseDimensions": { "T": -2 }, diff --git a/Common/UnitDefinitions/RotationalSpeed.json b/Common/UnitDefinitions/RotationalSpeed.json index 157fcb6c86..0ee2d13ab0 100644 --- a/Common/UnitDefinitions/RotationalSpeed.json +++ b/Common/UnitDefinitions/RotationalSpeed.json @@ -1,7 +1,7 @@ { "Name": "RotationalSpeed", "BaseUnit": "RadianPerSecond", - "XmlDoc": "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\").", + "XmlDocSummary": "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\").", "BaseDimensions": { "T": -1 }, diff --git a/Common/UnitDefinitions/RotationalStiffness.json b/Common/UnitDefinitions/RotationalStiffness.json index 191ff626f0..eeadfe573d 100644 --- a/Common/UnitDefinitions/RotationalStiffness.json +++ b/Common/UnitDefinitions/RotationalStiffness.json @@ -1,7 +1,7 @@ { "Name": "RotationalStiffness", "BaseUnit": "NewtonMeterPerRadian", - "XmlDoc": "https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness", + "XmlDocSummary": "https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/RotationalStiffnessPerLength.json b/Common/UnitDefinitions/RotationalStiffnessPerLength.json index 9b8e346e5e..791ee833a1 100644 --- a/Common/UnitDefinitions/RotationalStiffnessPerLength.json +++ b/Common/UnitDefinitions/RotationalStiffnessPerLength.json @@ -1,7 +1,7 @@ { "Name": "RotationalStiffnessPerLength", "BaseUnit": "NewtonMeterPerRadianPerMeter", - "XmlDoc": "https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness", + "XmlDocSummary": "https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness", "BaseDimensions": { "L": 1, "M": 1, diff --git a/Common/UnitDefinitions/Scalar.json b/Common/UnitDefinitions/Scalar.json index 1e954a5470..8c8a5ebea4 100644 --- a/Common/UnitDefinitions/Scalar.json +++ b/Common/UnitDefinitions/Scalar.json @@ -1,7 +1,7 @@ { "Name": "Scalar", "BaseUnit": "Amount", - "XmlDoc": "A way of representing a number of items.", + "XmlDocSummary": "A way of representing a number of items.", "Units": [ { "SingularName": "Amount", diff --git a/Common/UnitDefinitions/SolidAngle.json b/Common/UnitDefinitions/SolidAngle.json index a4cc4d7ac6..b19657d42a 100644 --- a/Common/UnitDefinitions/SolidAngle.json +++ b/Common/UnitDefinitions/SolidAngle.json @@ -1,7 +1,7 @@ { "Name": "SolidAngle", "BaseUnit": "Steradian", - "XmlDoc": "In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point.", + "XmlDocSummary": "In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Solid_angle", "Units": [ { diff --git a/Common/UnitDefinitions/SpecificEnergy.json b/Common/UnitDefinitions/SpecificEnergy.json index 5366fcce01..bdddb6bd1c 100644 --- a/Common/UnitDefinitions/SpecificEnergy.json +++ b/Common/UnitDefinitions/SpecificEnergy.json @@ -1,7 +1,7 @@ { "Name": "SpecificEnergy", "BaseUnit": "JoulePerKilogram", - "XmlDoc": "The SpecificEnergy", + "XmlDocSummary": "The SpecificEnergy", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Specific_energy", "BaseDimensions": { "L": 2, diff --git a/Common/UnitDefinitions/SpecificEntropy.json b/Common/UnitDefinitions/SpecificEntropy.json index c542fdf19f..1bcecf5c26 100644 --- a/Common/UnitDefinitions/SpecificEntropy.json +++ b/Common/UnitDefinitions/SpecificEntropy.json @@ -1,7 +1,7 @@ { "Name": "SpecificEntropy", "BaseUnit": "JoulePerKilogramKelvin", - "XmlDoc": "Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass.", + "XmlDocSummary": "Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass.", "BaseDimensions": { "L": 2, "T": -2, diff --git a/Common/UnitDefinitions/SpecificFuelConsumption.json b/Common/UnitDefinitions/SpecificFuelConsumption.json index e1bb389562..52516e863d 100644 --- a/Common/UnitDefinitions/SpecificFuelConsumption.json +++ b/Common/UnitDefinitions/SpecificFuelConsumption.json @@ -1,7 +1,7 @@ { "Name": "SpecificFuelConsumption", "BaseUnit": "GramPerKiloNewtonSecond", - "XmlDoc": "SFC is the fuel efficiency of an engine design with respect to thrust output", + "XmlDocSummary": "SFC is the fuel efficiency of an engine design with respect to thrust output", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Thrust-specific_fuel_consumption", "Units": [ { @@ -24,7 +24,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kg/(kgf·h)" ] + "Abbreviations": [ "kg/(kgf�h)" ] } ] }, @@ -37,8 +37,8 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/(kN·s)" ], - "AbbreviationsForPrefixes": { "Kilo": [ "kg/(kN·s)" ] } + "Abbreviations": [ "g/(kN�s)" ], + "AbbreviationsForPrefixes": { "Kilo": [ "kg/(kN�s)" ] } } ] } diff --git a/Common/UnitDefinitions/SpecificVolume.json b/Common/UnitDefinitions/SpecificVolume.json index 707740b3d2..a428f3355d 100644 --- a/Common/UnitDefinitions/SpecificVolume.json +++ b/Common/UnitDefinitions/SpecificVolume.json @@ -1,7 +1,7 @@ { "Name": "SpecificVolume", "BaseUnit": "CubicMeterPerKilogram", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 3, "M": -1 diff --git a/Common/UnitDefinitions/SpecificWeight.json b/Common/UnitDefinitions/SpecificWeight.json index 7a950d2116..3ff8a8f11a 100644 --- a/Common/UnitDefinitions/SpecificWeight.json +++ b/Common/UnitDefinitions/SpecificWeight.json @@ -1,7 +1,7 @@ { "Name": "SpecificWeight", "BaseUnit": "NewtonPerCubicMeter", - "XmlDoc": "The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume.", + "XmlDocSummary": "The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Specificweight", "BaseDimensions": { "L": -2, diff --git a/Common/UnitDefinitions/Speed.json b/Common/UnitDefinitions/Speed.json index f556e353f4..f7cffeedd7 100644 --- a/Common/UnitDefinitions/Speed.json +++ b/Common/UnitDefinitions/Speed.json @@ -1,7 +1,7 @@ { "Name": "Speed", "BaseUnit": "MeterPerSecond", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 1, "T": -1 diff --git a/Common/UnitDefinitions/StandardVolumeFlow.json b/Common/UnitDefinitions/StandardVolumeFlow.json index f607aeef1e..bf731df37e 100644 --- a/Common/UnitDefinitions/StandardVolumeFlow.json +++ b/Common/UnitDefinitions/StandardVolumeFlow.json @@ -1,7 +1,7 @@ { "Name": "StandardVolumeFlow", "BaseUnit": "StandardCubicMeterPerSecond", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "M": 1, "T": -1 diff --git a/Common/UnitDefinitions/Temperature.json b/Common/UnitDefinitions/Temperature.json index 01678cb38d..9a5ec73aee 100644 --- a/Common/UnitDefinitions/Temperature.json +++ b/Common/UnitDefinitions/Temperature.json @@ -1,7 +1,7 @@ { "Name": "Temperature", "BaseUnit": "Kelvin", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "GenerateArithmetic": false, "BaseDimensions": { "Θ": 1 diff --git a/Common/UnitDefinitions/TemperatureChangeRate.json b/Common/UnitDefinitions/TemperatureChangeRate.json index 013c35beb2..6359b24f2f 100644 --- a/Common/UnitDefinitions/TemperatureChangeRate.json +++ b/Common/UnitDefinitions/TemperatureChangeRate.json @@ -1,7 +1,7 @@ { "Name": "TemperatureChangeRate", "BaseUnit": "DegreeCelsiusPerSecond", - "XmlDoc": "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).", + "XmlDocSummary": "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).", "BaseDimensions": { "T": -1, "Θ": 1 diff --git a/Common/UnitDefinitions/TemperatureDelta.json b/Common/UnitDefinitions/TemperatureDelta.json index 514ca9e2e4..9215f4ec24 100644 --- a/Common/UnitDefinitions/TemperatureDelta.json +++ b/Common/UnitDefinitions/TemperatureDelta.json @@ -1,7 +1,7 @@ { "Name": "TemperatureDelta", "BaseUnit": "Kelvin", - "XmlDoc": "Difference between two temperatures. The conversions are different than for Temperature.", + "XmlDocSummary": "Difference between two temperatures. The conversions are different than for Temperature.", "BaseDimensions": { "Θ": 1 }, diff --git a/Common/UnitDefinitions/ThermalConductivity.json b/Common/UnitDefinitions/ThermalConductivity.json index 324aaf0cfb..46f26a935e 100644 --- a/Common/UnitDefinitions/ThermalConductivity.json +++ b/Common/UnitDefinitions/ThermalConductivity.json @@ -1,7 +1,7 @@ { "Name": "ThermalConductivity", "BaseUnit": "WattPerMeterKelvin", - "XmlDoc": "Thermal conductivity is the property of a material to conduct heat.", + "XmlDocSummary": "Thermal conductivity is the property of a material to conduct heat.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Thermal_Conductivity", "BaseDimensions": { "L": 1, diff --git a/Common/UnitDefinitions/ThermalResistance.json b/Common/UnitDefinitions/ThermalResistance.json index 05c2f46cf6..91da569fbc 100644 --- a/Common/UnitDefinitions/ThermalResistance.json +++ b/Common/UnitDefinitions/ThermalResistance.json @@ -1,7 +1,7 @@ { "Name": "ThermalResistance", "BaseUnit": "SquareMeterKelvinPerKilowatt", - "XmlDoc": "Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat.", + "XmlDocSummary": "Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat.", "BaseDimensions": { "M": -1, "T": 3, diff --git a/Common/UnitDefinitions/Torque.json b/Common/UnitDefinitions/Torque.json index 045ab226e7..4567759fe8 100644 --- a/Common/UnitDefinitions/Torque.json +++ b/Common/UnitDefinitions/Torque.json @@ -1,7 +1,7 @@ { "Name": "Torque", "BaseUnit": "NewtonMeter", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 2, "M": 1, diff --git a/Common/UnitDefinitions/TorquePerLength.json b/Common/UnitDefinitions/TorquePerLength.json index 45e658a17f..89728fdc7f 100644 --- a/Common/UnitDefinitions/TorquePerLength.json +++ b/Common/UnitDefinitions/TorquePerLength.json @@ -1,7 +1,7 @@ { "Name": "TorquePerLength", "BaseUnit": "NewtonMeterPerMeter", - "XmlDoc": "The magnitude of torque per unit length.", + "XmlDocSummary": "The magnitude of torque per unit length.", "BaseDimensions": { "L": 1, "M": 1, diff --git a/Common/UnitDefinitions/Turbidity.json b/Common/UnitDefinitions/Turbidity.json index 3ad79b6a35..0fd0b96e72 100644 --- a/Common/UnitDefinitions/Turbidity.json +++ b/Common/UnitDefinitions/Turbidity.json @@ -1,7 +1,7 @@ { "Name": "Turbidity", "BaseUnit": "NTU", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Turbidity", "Units": [ { diff --git a/Common/UnitDefinitions/VitaminA.json b/Common/UnitDefinitions/VitaminA.json index 852a90c551..b7220f9b46 100644 --- a/Common/UnitDefinitions/VitaminA.json +++ b/Common/UnitDefinitions/VitaminA.json @@ -1,7 +1,7 @@ { "Name": "VitaminA", "BaseUnit": "InternationalUnit", - "XmlDoc": "Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene.", + "XmlDocSummary": "Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene.", "Units": [ { "SingularName": "InternationalUnit", diff --git a/Common/UnitDefinitions/Volume.json b/Common/UnitDefinitions/Volume.json index c0e75ac8ad..cd8a4e9f67 100644 --- a/Common/UnitDefinitions/Volume.json +++ b/Common/UnitDefinitions/Volume.json @@ -1,7 +1,7 @@ { "Name": "Volume", "BaseUnit": "CubicMeter", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 3 }, diff --git a/Common/UnitDefinitions/VolumeConcentration.json b/Common/UnitDefinitions/VolumeConcentration.json index 3b051e34e0..d72be50504 100644 --- a/Common/UnitDefinitions/VolumeConcentration.json +++ b/Common/UnitDefinitions/VolumeConcentration.json @@ -1,7 +1,7 @@ { "Name": "VolumeConcentration", "BaseUnit": "DecimalFraction", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Concentration#Volume_concentration", "Units": [ { diff --git a/Common/UnitDefinitions/VolumeFlow.json b/Common/UnitDefinitions/VolumeFlow.json index 42e4e3de14..01b1148f6c 100644 --- a/Common/UnitDefinitions/VolumeFlow.json +++ b/Common/UnitDefinitions/VolumeFlow.json @@ -1,7 +1,7 @@ { "Name": "VolumeFlow", "BaseUnit": "CubicMeterPerSecond", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "BaseDimensions": { "L": 3, "T": -1 @@ -152,7 +152,7 @@ ] }, { - "SingularName": "MillionUsGallonsPerDay", + "SingularName": "MillionUsGallonPerDay", "PluralName": "MillionUsGallonsPerDay", "FromUnitToBaseFunc": "{x} / 22.824465227", "FromBaseToUnitFunc": "{x} * 22.824465227", diff --git a/Common/UnitDefinitions/VolumePerLength.json b/Common/UnitDefinitions/VolumePerLength.json index adc986c63f..2d4690e730 100644 --- a/Common/UnitDefinitions/VolumePerLength.json +++ b/Common/UnitDefinitions/VolumePerLength.json @@ -1,7 +1,7 @@ { "Name": "VolumePerLength", "BaseUnit": "CubicMeterPerMeter", - "XmlDoc": "Volume, typically of fluid, that a container can hold within a unit of length.", + "XmlDocSummary": "Volume, typically of fluid, that a container can hold within a unit of length.", "BaseDimensions": { "L": 2 }, diff --git a/Common/UnitDefinitions/VolumetricHeatCapacity.json b/Common/UnitDefinitions/VolumetricHeatCapacity.json index b6fb0629bb..0beebc41bd 100644 --- a/Common/UnitDefinitions/VolumetricHeatCapacity.json +++ b/Common/UnitDefinitions/VolumetricHeatCapacity.json @@ -1,7 +1,7 @@ { "Name": "VolumetricHeatCapacity", "BaseUnit": "JoulePerCubicMeterKelvin", - "XmlDoc": "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.", + "XmlDocSummary": "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.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Volumetric_heat_capacity", "BaseDimensions": { "M": 1, diff --git a/Common/UnitDefinitions/WarpingMomentOfInertia.json b/Common/UnitDefinitions/WarpingMomentOfInertia.json index 1d27de9a2a..b8245dc80b 100644 --- a/Common/UnitDefinitions/WarpingMomentOfInertia.json +++ b/Common/UnitDefinitions/WarpingMomentOfInertia.json @@ -1,7 +1,7 @@ { "Name": "WarpingMomentOfInertia", "BaseUnit": "MeterToTheSixth", - "XmlDoc": "A geometric property of an area that is used to determine the warping stress.", + "XmlDocSummary": "A geometric property of an area that is used to determine the warping stress.", "BaseDimensions": { "L": 6 }, diff --git a/Common/UnitEnumValues.g.json b/Common/UnitEnumValues.g.json index 1208d81785..6429a647b0 100644 --- a/Common/UnitEnumValues.g.json +++ b/Common/UnitEnumValues.g.json @@ -1611,7 +1611,8 @@ "UsGallonPerDay": 59, "UsGallonPerHour": 60, "UsGallonPerMinute": 61, - "UsGallonPerSecond": 62 + "UsGallonPerSecond": 62, + "MillionUsGallonPerDay": 66 }, "VolumeFlowPerArea": { "CubicFootPerMinutePerSquareFoot": 1, diff --git a/README.md b/README.md index 2da3fcb487..3899257d92 100644 --- a/README.md +++ b/README.md @@ -4,54 +4,52 @@ ## Units.NET -Add strongly typed quantities to your code and get merrily on with your life. +Add strongly typed quantities to your code and get merrily on with your life. No more magic constants found on Stack Overflow, no more second-guessing the unit of parameters and variables. +[Upgrading from 4.x to 5.x](https://github.com/angularsen/UnitsNet/wiki/Upgrading-from-4.x-to-5.x) ### Overview * [How to install](#how-to-install) -* [100+ quantities with 1200+ units](UnitsNet/GeneratedCode/Units) generated from [JSON](Common/UnitDefinitions/) by [C# CLI app](CodeGen) -* [8000+ unit tests](https://ci.appveyor.com/project/angularsen/unitsnet) on conversions and localizations -* Conforms to [Microsoft's open-source library guidance](https://docs.microsoft.com/en-us/dotnet/standard/library-guidance/), in particular: - * [SourceLink](https://github.com/dotnet/sourcelink) to step into source code of NuGet package while debugging - * [Strong naming](https://docs.microsoft.com/en-us/dotnet/standard/library-guidance/get-started#strong-naming) to make the library available to all developers -* Immutable structs that implement `IEquatable`, `IComparable` +* [100+ quantities with 1400+ units](UnitsNet/GeneratedCode/Units) generated from [JSON](Common/UnitDefinitions/) by [C# CLI app](CodeGen) +* [30k unit tests](https://dev.azure.com/unitsnet/Units.NET/_build?definitionId=1) * [Statically typed quantities and units](#static-typing) to avoid mistakes and communicate intent -* [Operator overloads](#operator-overloads) for arithmetic on quantities -* [Parse and ToString()](#culture) supports cultures and localization +* Immutable structs +* [Operator overloads](#operator-overloads) for arithmetic +* [Parse and ToString()](#culture) supports localization * [Dynamically parse and convert](#dynamic-parsing) quantities and units * [Extensible with custom units](#custom-units) * [Example: Creating a unit converter app](#example-app) * [Example: WPF app using IValueConverter to parse quantities from input](#example-wpf-app-using-ivalueconverter-to-parse-quantities-from-input) * [Precision and accuracy](#precision) -* [Serialize with JSON.NET](#serialization) +* [Serialize to JSON, XML and more](#serialization) * [Contribute](#contribute) if you are missing some units * [Continuous integration](#ci) posts status reports to pull requests and commits * [Who are using this?](#who-are-using) -### How to install +### Installing via NuGet -Run the following command in the [Package Manager Console](http://docs.nuget.org/docs/start-here/using-the-package-manager-console) or go to the [NuGet site](https://www.nuget.org/packages/UnitsNet/) for the complete release history. +Add it via CLI -![Install-Package UnitsNet](https://raw.githubusercontent.com/angularsen/UnitsNet/master/Docs/Images/install_package_unitsnet.png "Install-Package UnitsNet") + dotnet add package UnitsNet + +or go to [NuGet Gallery | UnitsNet](https://www.nuget.org/packages/UnitsNet) for detailed instructions. #### Build Targets * .NET Standard 2.0 -* .NET 4.0 * [.NET nanoFramework](https://www.nanoframework.net/) -* [Windows Runtime Component](https://docs.microsoft.com/en-us/windows/uwp/winrt-components/) for UWP apps (WinJS or C++) ### Static Typing ```C# -// Construct +// Construct Length meter = Length.FromMeters(1); Length twoMeters = new Length(2, LengthUnit.Meter); - + // Convert double cm = meter.Centimeters; // 100 double yards = meter.Yards; // 1.09361 @@ -62,8 +60,8 @@ double inches = meter.Inches; // 39.3701 string PrintPersonWeight(Mass weight) { // Compile error! Newtons belong to Force, not Mass. A common source of confusion. - double weightNewtons = weight.Newtons; - + double weightNewtons = weight.Newtons; + // Convert to the unit of choice - when you need it return $"You weigh {weight.Kilograms:F1} kg."; } @@ -86,7 +84,7 @@ RotationalSpeed r = Angle.FromDegrees(90) / TimeSpan.FromSeconds(2); ### Culture and Localization -The culture for abbreviations defaults to Thread.CurrentUICulture and falls back to US English if not defined. Thread.CurrentCulture affects number formatting unless a custom culture is specified. The relevant methods are: +The culture for abbreviations defaults to Thread.CurrentCulture and falls back to US English if not defined. Thread.CurrentCulture affects number formatting unless a custom culture is specified. The relevant methods are: * ToString() * GetAbbreviation() @@ -97,8 +95,9 @@ var usEnglish = new CultureInfo("en-US"); var russian = new CultureInfo("ru-RU"); var oneKg = Mass.FromKilograms(1); -// ToString() uses CurrentUICulture for abbreviation language and CurrentCulture for number formatting -Thread.CurrentThread.CurrentUICulture = russian; +// ToString() uses CurrentCulture for abbreviation language number formatting. This is consistent with the behavior of the .NET Framework, +// where DateTime.ToString() uses CurrentCulture for the whole string, likely because mixing an english date format with a russian month name might be confusing. +Thread.CurrentThread.CurrentCulture = russian; string kgRu = oneKg.ToString(); // "1 кг" // ToString() with specific culture and custom string format pattern @@ -167,7 +166,7 @@ All you need is the value and the unit enum value. IQuantity quantity = Quantity.From(3, LengthUnit.Centimeter); // Length if (Quantity.TryFrom(3, LengthUnit.Centimeter, out IQuantity quantity2)) -{ +{ } ``` #### Parse quantity @@ -253,13 +252,12 @@ Console.WriteLine(Convert(HowMuchUnit.Lots)); // 100 lts Console.WriteLine(Convert(HowMuchUnit.Tons)); // 10 tns ``` -### Example: Creating a dynamic unit converter app +### Example: Unit converter app [Source code](https://github.com/angularsen/UnitsNet/tree/master/Samples/UnitConverter.Wpf) for `Samples/UnitConverter.Wpf`
[Download](https://github.com/angularsen/UnitsNet/releases/tag/UnitConverterWpf%2F2018-11-09) (release 2018-11-09 for Windows) ![image](https://user-images.githubusercontent.com/787816/34920961-9b697004-f97b-11e7-9e9a-51ff7142969b.png) - This example shows how you can create a dynamic unit converter, where the user selects the quantity to convert, such as `Temperature`, then selects to convert from `DegreeCelsius` to `DegreeFahrenheit` and types in a numeric value for how many degrees Celsius to convert. The quantity list box contains `QuantityType` values such as `QuantityType.Length` and the two unit list boxes contain `Enum` values, such as `LengthUnit.Meter`. @@ -311,41 +309,13 @@ The tests accept an error up to 1E-5 for most units added so far. Exceptions inc For more details, see [Precision](https://github.com/angularsen/UnitsNet/wiki/Precision). +### Serialize to JSON, XML and more -### Serialization - -* `UnitsNet.Serialization.JsonNet` ([nuget](https://www.nuget.org/packages/UnitsNet.Serialization.JsonNet), [src](https://github.com/angularsen/UnitsNet/tree/master/UnitsNet.Serialization.JsonNet), [tests](https://github.com/angularsen/UnitsNet/tree/master/UnitsNet.Serialization.JsonNet.Tests)) for JSON.NET - -#### Example of JSON Serialization -```c# -var jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented}; -jsonSerializerSettings.Converters.Add(new UnitsNetIQuantityJsonConverter()); - -string json = JsonConvert.SerializeObject(new { Name = "Raiden", Weight = Mass.FromKilograms(90) }, jsonSerializerSettings); - -object obj = JsonConvert.DeserializeObject(json); -``` - -JSON output: -```json -{ - "Name": "Raiden", - "Weight": { - "Unit": "MassUnit.Kilogram", - "Value": 90.0 - } -} -``` +* [UnitsNet.Serialization.JsonNet](https://www.nuget.org/packages/UnitsNet.Serialization.JsonNet) with Json.NET (Newtonsoft) +* [DataContractSerializer](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datacontractserializer) XML +* [DataContractJsonSerializer](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.json.datacontractjsonserializer) JSON (not recommended*) -If you need to support deserializing into properties/fields of type `IComparable` instead of type `IQuantity`, then you can add -```c# -jsonSerializerSettings.Converters.Add(new UnitsNetIComparableJsonConverter()); -``` - -**Important!** -We cannot guarantee backwards compatibility, although we will strive to do that on a "best effort" basis and bumping the major nuget version when a change is necessary. - -The base unit of any unit should be treated as volatile as we have changed this several times in the history of this library already. Either to reduce precision errors of common units or to simplify code generation. An example is Mass, where the base unit was first Kilogram as this is the SI unit of mass, but in order to use powershell scripts to generate milligrams, nanograms etc. it was easier to choose Gram as the base unit of Mass. +Read more at [Serializing to JSON, XML and more](https://github.com/angularsen/UnitsNet/wiki/Serializing-to-JSON,-XML-and-more). ### Want To Contribute? @@ -368,7 +338,7 @@ It would be awesome to know who are using this library. If you would like your p #### Swing Catalyst and Motion Catalyst, Norway > Sports performance applications for Windows and iOS, that combine high-speed video with sensor data to bring facts into your training and visualize the invisible forces at work -> +> > Units.NET started here in 2007 when reading strain gauge measurements from force plates and has been very useful in integrating a number of different sensor types into our software and presenting the data in the user's preferred culture and units. https://www.swingcatalyst.com (for golf)
@@ -413,7 +383,7 @@ https://www.ansys.com/products/3d-design/ansys-discovery-live *- Tristan Milnthorp, Principal Software Architect (tristan.milnthorp@ansys.com)* #### Primoris Sigma Stargen -Stargen is a decades old software to create realistic planets and satellites from a given Star. It's based on work from various scientists and been used for years. Primoris Sigma Stargen is a C# port of the utility that makes it a Framework to extend it with new algorithms for planetary formation and physics equations. +Stargen is a decades old software to create realistic planets and satellites from a given Star. It's based on work from various scientists and been used for years. Primoris Sigma Stargen is a C# port of the utility that makes it a Framework to extend it with new algorithms for planetary formation and physics equations. https://github.com/ebfortin/primoris.universe.stargen @@ -432,11 +402,11 @@ https://kito.com #### Structural Analysis Format - SDK project -> The Structural Analysis Format (SAF) has been created to allow structural engineering applications to exchange data using a straight forward and simple to understand format. -> While inspired by IFC, SAF has its benefits that it's **easily modifyable** by the end-user _(it's an xlsx file)_, **well documented** and **easy to understand**. +> The Structural Analysis Format (SAF) has been created to allow structural engineering applications to exchange data using a straight forward and simple to understand format. +> While inspired by IFC, SAF has its benefits that it's **easily modifyable** by the end-user _(it's an xlsx file)_, **well documented** and **easy to understand**. > UnitsNet is used by the SDK provided by SCIA to facilitate import / export between metric & imperial systems -https://www.saf.guide +https://www.saf.guide https://github.com/StructuralAnalysisFormat/StructuralAnalysisFormat-SDK *- Dirk Schuermans, Software Engineer for [SCIA nv](https://www.scia.net)* diff --git a/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj b/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj deleted file mode 100644 index 4c6194f3df..0000000000 --- a/Samples/ConsoleApp-NetCore/ConsoleApp-NetCore.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - netcoreapp2.1 - Exe - ConsoleApp1.Program - - - - - - - - - - - diff --git a/Samples/ConsoleApp-NetCore/Program.cs b/Samples/ConsoleApp-NetCore/Program.cs deleted file mode 100644 index 4d4141d683..0000000000 --- a/Samples/ConsoleApp-NetCore/Program.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using UnitsNet; - -namespace ConsoleApp1 -{ - public class Program - { - public static void Main(string[] args) - { - Console.WriteLine("Length: " + Length.FromMeters(1)); - Console.ReadKey(true); - } - } -} diff --git a/Samples/WpfMVVMSample/WpfMVVMSample.sln b/Samples/MvvmSample.Wpf/MvvmSample.Wpf.sln similarity index 86% rename from Samples/WpfMVVMSample/WpfMVVMSample.sln rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf.sln index f6924a3728..d609483970 100644 --- a/Samples/WpfMVVMSample/WpfMVVMSample.sln +++ b/Samples/MvvmSample.Wpf/MvvmSample.Wpf.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27130.2010 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfMVVMSample", "WpfMVVMSample\WpfMVVMSample.csproj", "{B72F9215-70FF-4155-89BC-9A02CC550447}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvvmSample.Wpf", "MvvmSample.Wpf\MvvmSample.Wpf.csproj", "{B72F9215-70FF-4155-89BC-9A02CC550447}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/App.config b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/App.config similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/App.config rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/App.config diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/App.xaml b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/App.xaml similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/App.xaml rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/App.xaml diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/App.xaml.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/App.xaml.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/App.xaml.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/App.xaml.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Converters/EnumBindingSource.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Converters/EnumBindingSource.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/Converters/EnumBindingSource.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Converters/EnumBindingSource.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Converters/UnitToStringConverter.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Converters/UnitToStringConverter.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/Converters/UnitToStringConverter.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Converters/UnitToStringConverter.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/MainWindow.xaml b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MainWindow.xaml similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/MainWindow.xaml rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/MainWindow.xaml diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/MainWindow.xaml.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MainWindow.xaml.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/MainWindow.xaml.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/MainWindow.xaml.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/MainWindowViewModel.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MainWindowViewModel.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/MainWindowViewModel.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/MainWindowViewModel.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/WpfMVVMSample.csproj b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj similarity index 98% rename from Samples/WpfMVVMSample/WpfMVVMSample/WpfMVVMSample.csproj rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj index 4a1e7de4c5..d5edab10a6 100644 --- a/Samples/WpfMVVMSample/WpfMVVMSample/WpfMVVMSample.csproj +++ b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj @@ -7,8 +7,8 @@ {B72F9215-70FF-4155-89BC-9A02CC550447} WinExe WpfMVVMSample - WpfMVVMSample - v4.7.1 + MvvmSample.Wpf + v4.8 512 {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 4 diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/AssemblyInfo.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/AssemblyInfo.cs similarity index 96% rename from Samples/WpfMVVMSample/WpfMVVMSample/Properties/AssemblyInfo.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/AssemblyInfo.cs index 814762f31f..61146f9a9c 100644 --- a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/AssemblyInfo.cs +++ b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/AssemblyInfo.cs @@ -7,11 +7,11 @@ // 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("WpfMVVMSample")] +[assembly: AssemblyTitle("MvvmSample.Wpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("WpfMVVMSample")] +[assembly: AssemblyProduct("MvvmSample.Wpf")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/Resources.Designer.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Resources.Designer.cs similarity index 95% rename from Samples/WpfMVVMSample/WpfMVVMSample/Properties/Resources.Designer.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Resources.Designer.cs index 08f38a53e5..b95ae2d722 100644 --- a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/Resources.Designer.cs +++ b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Resources.Designer.cs @@ -39,7 +39,7 @@ internal Resources() { internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfMVVMSample.Properties.Resources", typeof(Resources).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MvvmSample.Wpf.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/Resources.resx b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Resources.resx similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/Properties/Resources.resx rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Resources.resx diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/Settings.Designer.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Settings.Designer.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/Properties/Settings.Designer.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Settings.Designer.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Properties/Settings.settings b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Settings.settings similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/Properties/Settings.settings rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Properties/Settings.settings diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/Settings/SettingsManager.cs b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/Settings/SettingsManager.cs similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/Settings/SettingsManager.cs rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/Settings/SettingsManager.cs diff --git a/Samples/WpfMVVMSample/WpfMVVMSample/packages.config b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/packages.config similarity index 100% rename from Samples/WpfMVVMSample/WpfMVVMSample/packages.config rename to Samples/MvvmSample.Wpf/MvvmSample.Wpf/packages.config diff --git a/Samples/WpfMVVMSample/Readme.md b/Samples/MvvmSample.Wpf/Readme.md similarity index 100% rename from Samples/WpfMVVMSample/Readme.md rename to Samples/MvvmSample.Wpf/Readme.md diff --git a/Samples/ConsoleApp-NetCore/build.bat b/Samples/MvvmSample.Wpf/build.bat similarity index 100% rename from Samples/ConsoleApp-NetCore/build.bat rename to Samples/MvvmSample.Wpf/build.bat diff --git a/Samples/Samples.sln b/Samples/Samples.sln index e125d7998a..2101631750 100644 --- a/Samples/Samples.sln +++ b/Samples/Samples.sln @@ -3,15 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27130.2020 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp-NetCore", "ConsoleApp-NetCore\ConsoleApp-NetCore.csproj", "{955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitConverter.Wpf", "UnitConverter.Wpf\UnitConverter.Wpf\UnitConverter.Wpf.csproj", "{D04EE35D-496A-4C83-A369-09B9B2BEAEEC}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfMVVMSample", "WpfMVVMSample\WpfMVVMSample\WpfMVVMSample.csproj", "{B72F9215-70FF-4155-89BC-9A02CC550447}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleConversionDemo.UWP.CSharp", "SimpleConversionDemo.UWP.CSharp\SimpleConversionDemo.UWP.CSharp.csproj", "{76255CC9-A854-441F-AF5C-2606509D3C5E}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvvmSample.Wpf", "MvvmSample.Wpf\MvvmSample.Wpf\MvvmSample.Wpf.csproj", "{B72F9215-70FF-4155-89BC-9A02CC550447}" EndProject -Project("{262852C6-CD72-467D-83FE-5EEB1973A190}") = "SimpleConversionDemo.UWP.WinJS", "SimpleConversionDemo.UWP.WinJS\SimpleConversionDemo.UWP.WinJS.jsproj", "{F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitConverter.Console", "UnitConverter.Console\UnitConverter.Console.csproj", "{B3141011-CEF2-46DE-B3DD-7FECD0D6108C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -25,20 +21,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|ARM.ActiveCfg = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|x64.ActiveCfg = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|x64.Build.0 = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|x86.ActiveCfg = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Debug|x86.Build.0 = Debug|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|Any CPU.Build.0 = Release|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|ARM.ActiveCfg = Release|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|x64.ActiveCfg = Release|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|x64.Build.0 = Release|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|x86.ActiveCfg = Release|Any CPU - {955A6CBF-C4E3-4C55-85C8-613E2CA4CCD7}.Release|x86.Build.0 = Release|Any CPU {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|Any CPU.Build.0 = Debug|Any CPU {D04EE35D-496A-4C83-A369-09B9B2BEAEEC}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -67,46 +49,22 @@ Global {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|x64.Build.0 = Release|Any CPU {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|x86.ActiveCfg = Release|Any CPU {B72F9215-70FF-4155-89BC-9A02CC550447}.Release|x86.Build.0 = Release|Any CPU - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|Any CPU.ActiveCfg = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|Any CPU.Build.0 = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|Any CPU.Deploy.0 = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|ARM.ActiveCfg = Debug|ARM - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|ARM.Build.0 = Debug|ARM - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|ARM.Deploy.0 = Debug|ARM - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|x64.ActiveCfg = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|x86.ActiveCfg = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|x86.Build.0 = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Debug|x86.Deploy.0 = Debug|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|Any CPU.ActiveCfg = Release|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|Any CPU.Build.0 = Release|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|Any CPU.Deploy.0 = Release|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|ARM.ActiveCfg = Release|ARM - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|ARM.Build.0 = Release|ARM - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|ARM.Deploy.0 = Release|ARM - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|x64.ActiveCfg = Release|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|x86.ActiveCfg = Release|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|x86.Build.0 = Release|x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E}.Release|x86.Deploy.0 = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|Any CPU.ActiveCfg = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|Any CPU.Build.0 = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|Any CPU.Deploy.0 = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|ARM.ActiveCfg = Debug|ARM - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|ARM.Build.0 = Debug|ARM - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|ARM.Deploy.0 = Debug|ARM - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|x64.ActiveCfg = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|x86.ActiveCfg = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|x86.Build.0 = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Debug|x86.Deploy.0 = Debug|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|Any CPU.ActiveCfg = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|Any CPU.Build.0 = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|Any CPU.Deploy.0 = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|ARM.ActiveCfg = Release|ARM - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|ARM.Build.0 = Release|ARM - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|ARM.Deploy.0 = Release|ARM - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|x64.ActiveCfg = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|x86.ActiveCfg = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|x86.Build.0 = Release|x86 - {F5B26152-A64B-42A8-8F19-D2EAFB94CBD1}.Release|x86.Deploy.0 = Release|x86 + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|ARM.ActiveCfg = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|ARM.Build.0 = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|x64.ActiveCfg = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|x64.Build.0 = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|x86.ActiveCfg = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Debug|x86.Build.0 = Debug|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|Any CPU.Build.0 = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|ARM.ActiveCfg = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|ARM.Build.0 = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x64.ActiveCfg = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x64.Build.0 = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x86.ActiveCfg = Release|Any CPU + {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/.gitignore b/Samples/SimpleConversionDemo.UWP.CSharp/.gitignore deleted file mode 100644 index 96382d195c..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/project.lock.json diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml b/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml deleted file mode 100644 index b1c066daf0..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml.cs b/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml.cs deleted file mode 100644 index 1fba308c44..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/App.xaml.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -namespace UWP -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = true; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/LockScreenLogo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/LockScreenLogo.scale-200.png deleted file mode 100644 index 735f57adb5..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/LockScreenLogo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/SplashScreen.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/SplashScreen.scale-200.png deleted file mode 100644 index 023e7f1fed..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/SplashScreen.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square150x150Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square150x150Logo.scale-200.png deleted file mode 100644 index af49fec1a5..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square150x150Logo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.scale-200.png deleted file mode 100644 index ce342a2ec8..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png deleted file mode 100644 index f6c02ce97e..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/StoreLogo.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/StoreLogo.png deleted file mode 100644 index 7385b56c0e..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/StoreLogo.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Wide310x150Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Wide310x150Logo.scale-200.png deleted file mode 100644 index 288995b397..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/Assets/Wide310x150Logo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml b/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml deleted file mode 100644 index 778b882e95..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml.cs b/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml.cs deleted file mode 100644 index d2e8c25c54..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/MainPage.xaml.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Windows.UI.Xaml.Controls; -using UnitsNet; -using UnitsNet.Units; - -namespace UWP -{ - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class MainPage : Page - { - /// - /// Example of public property returning WinRT component compatible type. - /// - public Temperature MyTemperature { get; set; } - - public MainPage() - { - InitializeComponent(); - - // Test some variations, From() constructors, Parse(), As() - string celsius = Temperature.FromDegreesCelsius(100).ToUnit(TemperatureUnit.DegreeCelsius).ToString(); - string fahrenheit = Temperature.Parse("100 °C").ToUnit(TemperatureUnit.DegreeFahrenheit).ToString(); - string kelvin = Temperature.FromDegreesCelsius(Temperature.Parse(fahrenheit).As(TemperatureUnit.DegreeCelsius)).ToUnit(TemperatureUnit.Kelvin).ToString(); - - // Arithmetic operators not allowed in WinRT Components, but SHOULD be allowed in UWP C# apps - // new Temperature(5) + new Temperature(6) - - MyTextBlock.Text = $"{celsius} = {fahrenheit} = {kelvin}"; - } - } -} diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Package.appxmanifest b/Samples/SimpleConversionDemo.UWP.CSharp/Package.appxmanifest deleted file mode 100644 index 4aa128459b..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/Package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - UWP - Andreas - Assets\StoreLogo.png - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Properties/AssemblyInfo.cs b/Samples/SimpleConversionDemo.UWP.CSharp/Properties/AssemblyInfo.cs deleted file mode 100644 index eaf72df06f..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// 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("UWP")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("UWP")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/Properties/Default.rd.xml b/Samples/SimpleConversionDemo.UWP.CSharp/Properties/Default.rd.xml deleted file mode 100644 index 80a960ce32..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/Properties/Default.rd.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/README.md b/Samples/SimpleConversionDemo.UWP.CSharp/README.md deleted file mode 100644 index e922422524..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Test app: UWP C# and .NET 4.6.1 - -Illustrates using `UnitsNet.WindowsRuntimeComponent` from an UWP C# app. -The Windows Runtime Component nuget can be consumed from C#, JavaScript and C++ UWP apps. - -NOTE: Normally for C# UWP apps you would use the more feature-rich `UnitsNet` nuget, since Windows Runtime Component -only supports some of the .NET BCL types and has many constraints on how the public API of the library can be declared. - -![image](https://user-images.githubusercontent.com/787816/35769617-e0bf05b4-090d-11e8-85e4-efdd7b90a6be.png) \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp.csproj b/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp.csproj deleted file mode 100644 index 19f9c3b450..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp.csproj +++ /dev/null @@ -1,141 +0,0 @@ - - - - - Debug - x86 - {76255CC9-A854-441F-AF5C-2606509D3C5E} - AppContainerExe - Properties - UWP - UWP - en-US - UAP - 10.0.16299.0 - 10.0.16299.0 - 14 - 512 - {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx - E98156EA0B8126C89A2653E1CBF645701A704E52 - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x86 - false - prompt - true - true - - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM - false - prompt - true - - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - ARM - false - prompt - true - true - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x64 - false - prompt - true - true - - - - - - - - - App.xaml - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - 14.0 - - - - \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx b/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx deleted file mode 100644 index 61cfb8eca2..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.CSharp/SimpleConversionDemo.UWP.CSharp_TemporaryKey.pfx and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/build.bat b/Samples/SimpleConversionDemo.UWP.CSharp/build.bat deleted file mode 100644 index 266afed369..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/build.bat +++ /dev/null @@ -1,12 +0,0 @@ -@echo off - -set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" - -for /f "usebackq tokens=*" %%i in (`%vswhere% -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do ( - set InstallDir=%%i -) - -if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" ( - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" /t:restore %* - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" %* -) \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.CSharp/project.json b/Samples/SimpleConversionDemo.UWP.CSharp/project.json deleted file mode 100644 index 6ff7189767..0000000000 --- a/Samples/SimpleConversionDemo.UWP.CSharp/project.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "6.1.9", - "UnitsNet.WindowsRuntimeComponent": "4.7.0" - }, - "frameworks": { - "uap10.0.16299": {} - }, - "runtimes": { - "win10-arm": {}, - "win10-arm-aot": {}, - "win10-x86": {}, - "win10-x86-aot": {}, - "win10-x64": {}, - "win10-x64-aot": {} - } -} \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/README.md b/Samples/SimpleConversionDemo.UWP.WinJS/README.md deleted file mode 100644 index 3ef8cccb4b..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Test app: UWP WinJS and .NET 4.7.1 - -Illustrates using `UnitsNet.WindowsRuntimeComponent` from an UWP JavaScript app. -The Windows Runtime Component nuget can be consumed from C#, JavaScript and C++ UWP apps. - - -![image](https://user-images.githubusercontent.com/787816/35769565-700e4582-090d-11e8-80f6-19a4f06dea9e.png) - -### Remarks -For some reason, out of the box UWP WinJS projects come with `packages.config` and it simply does not work without manually changing to `SpecificVersion=False` for each reference. -As a workaround, I have instead replaced it with `project.json` file, which although is end-of-life works better. I suspect the whole WinJS platform is also nearing end-of-life really.. - -Read more here: https://github.com/NuGet/Home/issues/2406 \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS.jsproj b/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS.jsproj deleted file mode 100644 index 4b820238c5..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS.jsproj +++ /dev/null @@ -1,92 +0,0 @@ - - - - - Debug - AnyCPU - - - Debug - ARM - - - Debug - x64 - - - Debug - x86 - - - Release - AnyCPU - - - Release - ARM - true - - - Release - x64 - true - - - Release - x86 - true - - - - f5b26152-a64b-42a8-8f19-d2eafb94cbd1 - - - - 15.0 - - - - - UAP - 10.0.16299.0 - 10.0.16299.0 - $(VersionNumberMajor).$(VersionNumberMinor) - en-US - SimpleConversionDemo.UWP.WinJS_TemporaryKey.pfx - 233FD264CDB1D145E2BAA90728A41382699F2046 - - - - Designer - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS_TemporaryKey.pfx b/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS_TemporaryKey.pfx deleted file mode 100644 index 8cdfed649f..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/SimpleConversionDemo.UWP.WinJS_TemporaryKey.pfx and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/build.bat b/Samples/SimpleConversionDemo.UWP.WinJS/build.bat deleted file mode 100644 index 266afed369..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/build.bat +++ /dev/null @@ -1,12 +0,0 @@ -@echo off - -set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" - -for /f "usebackq tokens=*" %%i in (`%vswhere% -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do ( - set InstallDir=%%i -) - -if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" ( - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" /t:restore %* - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" %* -) \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/css/default.css b/Samples/SimpleConversionDemo.UWP.WinJS/css/default.css deleted file mode 100644 index 46800d16ad..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/css/default.css +++ /dev/null @@ -1,2 +0,0 @@ -body { -} diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/LockScreenLogo.scale-200.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/LockScreenLogo.scale-200.png deleted file mode 100644 index 735f57adb5..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/LockScreenLogo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/SplashScreen.scale-200.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/SplashScreen.scale-200.png deleted file mode 100644 index 023e7f1fed..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/SplashScreen.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/Square150x150Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/Square150x150Logo.scale-200.png deleted file mode 100644 index af49fec1a5..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/Square150x150Logo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/Square44x44Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/Square44x44Logo.scale-200.png deleted file mode 100644 index ce342a2ec8..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/Square44x44Logo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/Square44x44Logo.targetsize-24_altform-unplated.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/Square44x44Logo.targetsize-24_altform-unplated.png deleted file mode 100644 index f6c02ce97e..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/Square44x44Logo.targetsize-24_altform-unplated.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/StoreLogo.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/StoreLogo.png deleted file mode 100644 index 7385b56c0e..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/StoreLogo.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/images/Wide310x150Logo.scale-200.png b/Samples/SimpleConversionDemo.UWP.WinJS/images/Wide310x150Logo.scale-200.png deleted file mode 100644 index 288995b397..0000000000 Binary files a/Samples/SimpleConversionDemo.UWP.WinJS/images/Wide310x150Logo.scale-200.png and /dev/null differ diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/index.html b/Samples/SimpleConversionDemo.UWP.WinJS/index.html deleted file mode 100644 index 38fe94b6ba..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/index.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - WinJS_471 - - - - - - - - - - -
-

Content goes here

-
- - diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/js/main.js b/Samples/SimpleConversionDemo.UWP.WinJS/js/main.js deleted file mode 100644 index c85ea57d1b..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/js/main.js +++ /dev/null @@ -1,66 +0,0 @@ -// For an introduction to the Blank template, see the following documentation: -// https://go.microsoft.com/fwlink/?LinkId=232509 - -(function () { - "use strict"; - - var app = WinJS.Application; - var activation = Windows.ApplicationModel.Activation; - var isFirstActivation = true; - - app.onactivated = function (args) { - if (args.detail.kind === activation.ActivationKind.voiceCommand) { - // TODO: Handle relevant ActivationKinds. For example, if your app can be started by voice commands, - // this is a good place to decide whether to populate an input field or choose a different initial view. - } - else if (args.detail.kind === activation.ActivationKind.launch) { - // A Launch activation happens when the user launches your app via the tile - // or invokes a toast notification by clicking or tapping on the body. - if (args.detail.arguments) { - // TODO: If the app supports toasts, use this value from the toast payload to determine where in the app - // to take the user in response to them invoking a toast notification. - } - else if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) { - // TODO: This application had been suspended and was then terminated to reclaim memory. - // To create a smooth user experience, restore application state here so that it looks like the app never stopped running. - // Note: You may want to record the time when the app was last suspended and only restore state if they've returned after a short period. - } - } - - if (!args.detail.prelaunchActivated) { - // TODO: If prelaunchActivated were true, it would mean the app was prelaunched in the background as an optimization. - // In that case it would be suspended shortly thereafter. - // Any long-running operations (like expensive network or disk I/O) or changes to user state which occur at launch - // should be done here (to avoid doing them in the prelaunch case). - // Alternatively, this work can be done in a resume or visibilitychanged handler. - } - - if (isFirstActivation) { - // TODO: The app was activated and had not been running. Do general startup initialization here. - document.addEventListener("visibilitychange", onVisibilityChanged); - args.setPromise(WinJS.UI.processAll()); - } - - var t = UnitsNet.Temperature.fromDegreesCelsius(100); - var unit = UnitsNet.Units.TemperatureUnit; - document.getElementById('label').innerHTML = t.toUnit(unit.degreeCelsius).toString() + ' = ' + t.toUnit(unit.degreeFahrenheit).toString() + ' = ' + t.toUnit(unit.kelvin).toString(); - - - isFirstActivation = false; - }; - - function onVisibilityChanged(args) { - if (!document.hidden) { - // TODO: The app just became visible. This may be a good time to refresh the view. - } - } - - app.oncheckpoint = function (args) { - // TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here. - // You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension. - // If you need to complete an asynchronous operation before your application is suspended, call args.setPromise(). - }; - - app.start(); - -})(); diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/lib/winjs-4.0.1/css/ui-dark.css b/Samples/SimpleConversionDemo.UWP.WinJS/lib/winjs-4.0.1/css/ui-dark.css deleted file mode 100644 index 991c9316d3..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/lib/winjs-4.0.1/css/ui-dark.css +++ /dev/null @@ -1,7304 +0,0 @@ -/* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ -@keyframes WinJS-node-inserted { - from { - outline-color: #000; - } - to { - outline-color: #001; - } -} -@keyframes WinJS-opacity-in { - from { - opacity: 0; - } - to { - opacity: 1; - } -} -@keyframes WinJS-opacity-out { - from { - opacity: 1; - } - to { - opacity: 0; - } -} -@keyframes WinJS-scale-up { - from { - transform: scale(0.85); - } - to { - transform: scale(1); - } -} -@keyframes WinJS-scale-down { - from { - transform: scale(1); - } - to { - transform: scale(0.85); - } -} -@keyframes WinJS-default-remove { - from { - transform: translateX(11px); - } - to { - transform: none; - } -} -@keyframes WinJS-default-remove-rtl { - from { - transform: translateX(-11px); - } - to { - transform: none; - } -} -@keyframes WinJS-default-apply { - from { - transform: none; - } - to { - transform: translateX(11px); - } -} -@keyframes WinJS-default-apply-rtl { - from { - transform: none; - } - to { - transform: translateX(-11px); - } -} -@keyframes WinJS-showEdgeUI { - from { - transform: translateY(-70px); - } - to { - transform: none; - } -} -@keyframes WinJS-showPanel { - from { - transform: translateX(364px); - } - to { - transform: none; - } -} -@keyframes WinJS-showPanel-rtl { - from { - transform: translateX(-364px); - } - to { - transform: none; - } -} -@keyframes WinJS-hideEdgeUI { - from { - transform: none; - } - to { - transform: translateY(-70px); - } -} -@keyframes WinJS-hidePanel { - from { - transform: none; - } - to { - transform: translateX(364px); - } -} -@keyframes WinJS-hidePanel-rtl { - from { - transform: none; - } - to { - transform: translateX(-364px); - } -} -@keyframes WinJS-showPopup { - from { - transform: translateY(50px); - } - to { - transform: none; - } -} -@keyframes WinJS-dragSourceEnd { - from { - transform: translateX(11px) scale(1.05); - } - to { - transform: none; - } -} -@keyframes WinJS-dragSourceEnd-rtl { - from { - transform: translateX(-11px) scale(1.05); - } - to { - transform: none; - } -} -@keyframes WinJS-enterContent { - from { - transform: translateY(28px); - } - to { - transform: none; - } -} -@keyframes WinJS-exit { - from { - transform: none; - } - to { - transform: none; - } -} -@keyframes WinJS-enterPage { - from { - transform: translateY(28px); - } - to { - transform: none; - } -} -@keyframes WinJS-updateBadge { - from { - transform: translateY(24px); - } - to { - transform: none; - } -} -@-webkit-keyframes WinJS-node-inserted { - from { - outline-color: #000; - } - to { - outline-color: #001; - } -} -@-webkit-keyframes -webkit-WinJS-opacity-in { - from { - opacity: 0; - } - to { - opacity: 1; - } -} -@-webkit-keyframes -webkit-WinJS-opacity-out { - from { - opacity: 1; - } - to { - opacity: 0; - } -} -@-webkit-keyframes -webkit-WinJS-scale-up { - from { - -webkit-transform: scale(0.85); - } - to { - -webkit-transform: scale(1); - } -} -@-webkit-keyframes -webkit-WinJS-scale-down { - from { - -webkit-transform: scale(1); - } - to { - -webkit-transform: scale(0.85); - } -} -@-webkit-keyframes -webkit-WinJS-default-remove { - from { - -webkit-transform: translateX(11px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-default-remove-rtl { - from { - -webkit-transform: translateX(-11px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-default-apply { - from { - -webkit-transform: none; - } - to { - -webkit-transform: translateX(11px); - } -} -@-webkit-keyframes -webkit-WinJS-default-apply-rtl { - from { - -webkit-transform: none; - } - to { - -webkit-transform: translateX(-11px); - } -} -@-webkit-keyframes -webkit-WinJS-showEdgeUI { - from { - -webkit-transform: translateY(-70px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-showPanel { - from { - -webkit-transform: translateX(364px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-showPanel-rtl { - from { - -webkit-transform: translateX(-364px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-hideEdgeUI { - from { - -webkit-transform: none; - } - to { - -webkit-transform: translateY(-70px); - } -} -@-webkit-keyframes -webkit-WinJS-hidePanel { - from { - -webkit-transform: none; - } - to { - -webkit-transform: translateX(364px); - } -} -@-webkit-keyframes -webkit-WinJS-hidePanel-rtl { - from { - -webkit-transform: none; - } - to { - -webkit-transform: translateX(-364px); - } -} -@-webkit-keyframes -webkit-WinJS-showPopup { - from { - -webkit-transform: translateY(50px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-dragSourceEnd { - from { - -webkit-transform: translateX(11px) scale(1.05); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-dragSourceEnd-rtl { - from { - -webkit-transform: translateX(-11px) scale(1.05); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-enterContent { - from { - -webkit-transform: translateY(28px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-exit { - from { - -webkit-transform: none; - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-enterPage { - from { - -webkit-transform: translateY(28px); - } - to { - -webkit-transform: none; - } -} -@-webkit-keyframes -webkit-WinJS-updateBadge { - from { - -webkit-transform: translateY(24px); - } - to { - -webkit-transform: none; - } -} -@font-face { - font-family: "Segoe UI Command"; - src: local("Segoe MDL2 Assets"); - font-weight: normal; - font-style: normal; -} -@font-face { - font-family: "Symbols"; - src: url(../fonts/Symbols.ttf); -} -.win-type-header, -.win-h1 { - font-size: 46px; - font-weight: 200; - line-height: 1.216; - letter-spacing: 0px; -} -.win-type-subheader, -.win-h2 { - font-size: 34px; - font-weight: 200; - line-height: 1.176; -} -.win-type-title, -.win-h3 { - font-size: 24px; - font-weight: 300; - line-height: 1.167; -} -.win-type-subtitle, -.win-h4 { - font-size: 20px; - font-weight: 400; - line-height: 1.2; -} -.win-type-body, -.win-h6 { - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-type-base, -.win-h5 { - font-size: 15px; - font-weight: 500; - line-height: 1.333; -} -.win-type-caption { - font-size: 12px; - font-weight: 400; - line-height: 1.167; -} -@font-face { - font-family: "Segoe UI"; - font-weight: 200; - src: local("Segoe UI Light"); -} -@font-face { - font-family: "Segoe UI"; - font-weight: 300; - src: local("Segoe UI Semilight"); -} -@font-face { - font-family: "Segoe UI"; - font-weight: 400; - src: local("Segoe UI"); -} -@font-face { - font-family: "Segoe UI"; - font-weight: 500; - src: local("Segoe UI Semibold"); -} -@font-face { - font-family: "Segoe UI"; - font-weight: 600; - src: local("Segoe UI Bold"); -} -@font-face { - font-family: "Segoe UI"; - font-style: italic; - font-weight: 400; - src: local("Segoe UI Italic"); -} -@font-face { - font-family: "Segoe UI"; - font-style: italic; - font-weight: 700; - src: local("Segoe UI Bold Italic"); -} -@font-face { - font-family: "Microsoft Yahei UI"; - font-weight: 200; - src: local("Microsoft Yahei UI Light"); -} -@font-face { - font-family: "Microsoft Yahei UI"; - font-weight: 300; - src: local("Microsoft Yahei UI"); -} -@font-face { - font-family: "Microsoft Yahei UI"; - font-weight: 500; - src: local("Microsoft Yahei UI"); -} -@font-face { - font-family: "Microsoft Yahei UI"; - font-weight: 600; - src: local("Microsoft Yahei UI Bold"); -} -@font-face { - font-family: "Microsoft JhengHei UI"; - font-weight: 200; - src: local("Microsoft JhengHei UI Light"); -} -@font-face { - font-family: "Microsoft JhengHei UI"; - font-weight: 300; - src: local("Microsoft JhengHei UI"); -} -@font-face { - font-family: "Microsoft JhengHei UI"; - font-weight: 500; - src: local("Microsoft JhengHei UI"); -} -@font-face { - font-family: "Microsoft JhengHei UI"; - font-weight: 600; - src: local("Microsoft JhengHei UI Bold"); -} -.win-type-header:-ms-lang(am, ti), -.win-type-subheader:-ms-lang(am, ti), -.win-type-title:-ms-lang(am, ti), -.win-type-subtitle:-ms-lang(am, ti), -.win-type-base:-ms-lang(am, ti), -.win-type-body:-ms-lang(am, ti), -.win-type-caption:-ms-lang(am, ti), -.win-h1:-ms-lang(am, ti), -.win-h2:-ms-lang(am, ti), -.win-h3:-ms-lang(am, ti), -.win-h4:-ms-lang(am, ti), -.win-h5:-ms-lang(am, ti), -.win-h6:-ms-lang(am, ti), -.win-button:-ms-lang(am, ti), -.win-dropdown:-ms-lang(am, ti), -.win-textbox:-ms-lang(am, ti), -.win-link:-ms-lang(am, ti), -.win-textarea:-ms-lang(am, ti) { - font-family: "Ebrima", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-type-subheader:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-type-title:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-type-subtitle:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-type-base:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-type-body:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-type-caption:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-h1:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-h2:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-h3:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-h4:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-h5:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-h6:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-button:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-dropdown:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-textbox:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-link:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te), -.win-textarea:-ms-lang(as, bn, gu, hi, kn, kok, ml, mr, ne, or, pa, sat-Olck, si, srb-Sora, ta, te) { - font-family: "Nirmala UI", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(chr-CHER-US), -.win-type-subheader:-ms-lang(chr-CHER-US), -.win-type-title:-ms-lang(chr-CHER-US), -.win-type-subtitle:-ms-lang(chr-CHER-US), -.win-type-base:-ms-lang(chr-CHER-US), -.win-type-body:-ms-lang(chr-CHER-US), -.win-type-caption:-ms-lang(chr-CHER-US), -.win-h1:-ms-lang(chr-CHER-US), -.win-h2:-ms-lang(chr-CHER-US), -.win-h3:-ms-lang(chr-CHER-US), -.win-h4:-ms-lang(chr-CHER-US), -.win-h5:-ms-lang(chr-CHER-US), -.win-h6:-ms-lang(chr-CHER-US), -.win-button:-ms-lang(chr-CHER-US), -.win-dropdown:-ms-lang(chr-CHER-US), -.win-textbox:-ms-lang(chr-CHER-US), -.win-link:-ms-lang(chr-CHER-US), -.win-textarea:-ms-lang(chr-CHER-US) { - font-family: "Gadugi", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(ja), -.win-type-subheader:-ms-lang(ja), -.win-type-title:-ms-lang(ja), -.win-type-subtitle:-ms-lang(ja), -.win-type-base:-ms-lang(ja), -.win-type-body:-ms-lang(ja), -.win-type-caption:-ms-lang(ja), -.win-h1:-ms-lang(ja), -.win-h2:-ms-lang(ja), -.win-h3:-ms-lang(ja), -.win-h4:-ms-lang(ja), -.win-h5:-ms-lang(ja), -.win-h6:-ms-lang(ja), -.win-button:-ms-lang(ja), -.win-dropdown:-ms-lang(ja), -.win-textbox:-ms-lang(ja), -.win-link:-ms-lang(ja), -.win-textarea:-ms-lang(ja) { - font-family: "Yu Gothic UI", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(km, lo, th, bug-Bugi), -.win-type-subheader:-ms-lang(km, lo, th, bug-Bugi), -.win-type-title:-ms-lang(km, lo, th, bug-Bugi), -.win-type-subtitle:-ms-lang(km, lo, th, bug-Bugi), -.win-type-base:-ms-lang(km, lo, th, bug-Bugi), -.win-type-body:-ms-lang(km, lo, th, bug-Bugi), -.win-type-caption:-ms-lang(km, lo, th, bug-Bugi), -.win-h1:-ms-lang(km, lo, th, bug-Bugi), -.win-h2:-ms-lang(km, lo, th, bug-Bugi), -.win-h3:-ms-lang(km, lo, th, bug-Bugi), -.win-h4:-ms-lang(km, lo, th, bug-Bugi), -.win-h5:-ms-lang(km, lo, th, bug-Bugi), -.win-h6:-ms-lang(km, lo, th, bug-Bugi), -.win-button:-ms-lang(km, lo, th, bug-Bugi), -.win-dropdown:-ms-lang(km, lo, th, bug-Bugi), -.win-textbox:-ms-lang(km, lo, th, bug-Bugi), -.win-link:-ms-lang(km, lo, th, bug-Bugi), -.win-textarea:-ms-lang(km, lo, th, bug-Bugi) { - font-family: "Leelawadee UI", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(ko), -.win-type-subheader:-ms-lang(ko), -.win-type-title:-ms-lang(ko), -.win-type-subtitle:-ms-lang(ko), -.win-type-base:-ms-lang(ko), -.win-type-body:-ms-lang(ko), -.win-type-caption:-ms-lang(ko), -.win-h1:-ms-lang(ko), -.win-h2:-ms-lang(ko), -.win-h3:-ms-lang(ko), -.win-h4:-ms-lang(ko), -.win-h5:-ms-lang(ko), -.win-h6:-ms-lang(ko), -.win-button:-ms-lang(ko), -.win-dropdown:-ms-lang(ko), -.win-textbox:-ms-lang(ko), -.win-link:-ms-lang(ko), -.win-textarea:-ms-lang(ko) { - font-family: "Malgun Gothic", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(jv-Java), -.win-type-subheader:-ms-lang(jv-Java), -.win-type-title:-ms-lang(jv-Java), -.win-type-subtitle:-ms-lang(jv-Java), -.win-type-base:-ms-lang(jv-Java), -.win-type-body:-ms-lang(jv-Java), -.win-type-caption:-ms-lang(jv-Java), -.win-h1:-ms-lang(jv-Java), -.win-h2:-ms-lang(jv-Java), -.win-h3:-ms-lang(jv-Java), -.win-h4:-ms-lang(jv-Java), -.win-h5:-ms-lang(jv-Java), -.win-h6:-ms-lang(jv-Java), -.win-button:-ms-lang(jv-Java), -.win-dropdown:-ms-lang(jv-Java), -.win-textbox:-ms-lang(jv-Java), -.win-link:-ms-lang(jv-Java), -.win-textarea:-ms-lang(jv-Java) { - font-family: "Javanese Text", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(cop-Copt), -.win-type-subheader:-ms-lang(cop-Copt), -.win-type-title:-ms-lang(cop-Copt), -.win-type-subtitle:-ms-lang(cop-Copt), -.win-type-base:-ms-lang(cop-Copt), -.win-type-body:-ms-lang(cop-Copt), -.win-type-caption:-ms-lang(cop-Copt), -.win-h1:-ms-lang(cop-Copt), -.win-h2:-ms-lang(cop-Copt), -.win-h3:-ms-lang(cop-Copt), -.win-h4:-ms-lang(cop-Copt), -.win-h5:-ms-lang(cop-Copt), -.win-h6:-ms-lang(cop-Copt), -.win-button:-ms-lang(cop-Copt), -.win-dropdown:-ms-lang(cop-Copt), -.win-textbox:-ms-lang(cop-Copt), -.win-link:-ms-lang(cop-Copt), -.win-textarea:-ms-lang(cop-Copt) { - font-family: "Segoe MDL2 Assets", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-type-subheader:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-type-title:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-type-subtitle:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-type-base:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-type-body:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-type-caption:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-h1:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-h2:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-h3:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-h4:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-h5:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-h6:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-button:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-dropdown:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-textbox:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-link:-ms-lang(zh-CN, zh-Hans, zh-SG), -.win-textarea:-ms-lang(zh-CN, zh-Hans, zh-SG) { - font-family: "Microsoft YaHei UI", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -.win-type-header:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-type-subheader:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-type-title:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-type-subtitle:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-type-base:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-type-body:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-type-caption:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-h1:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-h2:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-h3:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-h4:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-h5:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-h6:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-button:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-dropdown:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-textbox:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-link:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO), -.win-textarea:-ms-lang(zh-HK, zh-TW, zh-Hant, zh-MO) { - font-family: "Microsoft JhengHei UI", "Ebrima", "Nirmala UI", "Gadugi", "Segoe UI Emoji", "Segoe MDL2 Assets", "Symbols", "Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Leelawadee UI", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "Segoe UI Historic", "Estrangelo Edessa", "Microsoft Himalaya", "Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Tai Le", "Microsoft Yi Baiti", "Mongolian Baiti", "MV Boli", "Myanmar Text", "Javanese Text", "Cambria Math"; -} -html, -body { - width: 100%; - height: 100%; - margin: 0px; - cursor: default; - -webkit-touch-callout: none; - -ms-scroll-translation: vertical-to-horizontal; - -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -} -html { - overflow: hidden; - direction: ltr; -} -html:lang(ar), -html:lang(dv), -html:lang(fa), -html:lang(he), -html:lang(ku-Arab), -html:lang(pa-Arab), -html:lang(prs), -html:lang(ps), -html:lang(sd-Arab), -html:lang(syr), -html:lang(ug), -html:lang(ur), -html:lang(qps-plocm) { - direction: rtl; -} -body { - -ms-content-zooming: none; -} -iframe { - border: 0; -} -.win-type-header, -.win-type-subheader, -.win-type-title, -.win-type-subtitle, -.win-type-base, -.win-type-body, -.win-type-caption, -.win-h1, -.win-h2, -.win-h3, -.win-h4, -.win-h5, -.win-h6, -.win-button, -.win-dropdown, -.win-textbox, -.win-link, -.win-textarea { - font-family: "Segoe UI", sans-serif, "Segoe MDL2 Assets", "Symbols"; -} -.win-textbox, -.win-textarea { - -ms-user-select: element; - border-style: solid; - border-width: 2px; - border-radius: 0; - margin: 8px 0px; - width: 296px; - min-width: 64px; - min-height: 28px; - background-clip: border-box; - box-sizing: border-box; - padding: 3px 6px 5px 10px; - outline: 0; - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-textbox::-ms-value { - margin: 0; - padding: 0; -} -.win-textbox::-ms-clear, -.win-textbox::-ms-reveal { - padding-right: 2px; - margin-right: -8px; - margin-left: 2px; - margin-top: -8px; - margin-bottom: -8px; - width: 30px; - height: 32px; -} -.win-textbox:lang(ar)::-ms-clear, -.win-textbox:lang(dv)::-ms-clear, -.win-textbox:lang(fa)::-ms-clear, -.win-textbox:lang(he)::-ms-clear, -.win-textbox:lang(ku-Arab)::-ms-clear, -.win-textbox:lang(pa-Arab)::-ms-clear, -.win-textbox:lang(prs)::-ms-clear, -.win-textbox:lang(ps)::-ms-clear, -.win-textbox:lang(sd-Arab)::-ms-clear, -.win-textbox:lang(syr)::-ms-clear, -.win-textbox:lang(ug)::-ms-clear, -.win-textbox:lang(ur)::-ms-clear, -.win-textbox:lang(qps-plocm)::-ms-clear, -.win-textbox:lang(ar)::-ms-reveal, -.win-textbox:lang(dv)::-ms-reveal, -.win-textbox:lang(fa)::-ms-reveal, -.win-textbox:lang(he)::-ms-reveal, -.win-textbox:lang(ku-Arab)::-ms-reveal, -.win-textbox:lang(pa-Arab)::-ms-reveal, -.win-textbox:lang(prs)::-ms-reveal, -.win-textbox:lang(ps)::-ms-reveal, -.win-textbox:lang(sd-Arab)::-ms-reveal, -.win-textbox:lang(syr)::-ms-reveal, -.win-textbox:lang(ug)::-ms-reveal, -.win-textbox:lang(ur)::-ms-reveal, -.win-textbox:lang(qps-plocm)::-ms-reveal { - margin-left: -8px; - margin-right: 2px; -} -.win-textarea { - resize: none; - overflow-y: auto; -} -.win-radio, -.win-checkbox { - width: 20px; - height: 20px; - margin-right: 8px; - margin-top: 12px; - margin-bottom: 12px; -} -.win-radio:lang(ar), -.win-checkbox:lang(ar), -.win-radio:lang(dv), -.win-checkbox:lang(dv), -.win-radio:lang(fa), -.win-checkbox:lang(fa), -.win-radio:lang(he), -.win-checkbox:lang(he), -.win-radio:lang(ku-Arab), -.win-checkbox:lang(ku-Arab), -.win-radio:lang(pa-Arab), -.win-checkbox:lang(pa-Arab), -.win-radio:lang(prs), -.win-checkbox:lang(prs), -.win-radio:lang(ps), -.win-checkbox:lang(ps), -.win-radio:lang(sd-Arab), -.win-checkbox:lang(sd-Arab), -.win-radio:lang(syr), -.win-checkbox:lang(syr), -.win-radio:lang(ug), -.win-checkbox:lang(ug), -.win-radio:lang(ur), -.win-checkbox:lang(ur), -.win-radio:lang(qps-plocm), -.win-checkbox:lang(qps-plocm) { - margin-left: 8px; - margin-right: 0px; -} -.win-radio::-ms-check, -.win-checkbox::-ms-check { - border-style: solid; - display: inline-block; - border-width: 2px; - background-clip: border-box; -} -.win-button { - border-style: solid; - margin: 0px; - min-height: 32px; - min-width: 120px; - padding: 4px 8px; - border-width: 2px; - background-clip: border-box; - border-radius: 0; - touch-action: manipulation; - -webkit-appearance: none; - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-button.win-button-file { - border: none; - min-width: 100px; - min-height: 20px; - width: 340px; - height: 32px; - padding: 0px; - margin: 7px 8px 21px 8px; - background-clip: padding-box; -} -.win-button.win-button-file::-ms-value { - margin: 0; - border-width: 2px; - border-style: solid; - border-right-style: none; - border-radius: 0; - background-clip: border-box; - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-button.win-button-file:lang(ar)::-ms-value, -.win-button.win-button-file:lang(dv)::-ms-value, -.win-button.win-button-file:lang(fa)::-ms-value, -.win-button.win-button-file:lang(he)::-ms-value, -.win-button.win-button-file:lang(ku-Arab)::-ms-value, -.win-button.win-button-file:lang(pa-Arab)::-ms-value, -.win-button.win-button-file:lang(prs)::-ms-value, -.win-button.win-button-file:lang(ps)::-ms-value, -.win-button.win-button-file:lang(sd-Arab)::-ms-value, -.win-button.win-button-file:lang(syr)::-ms-value, -.win-button.win-button-file:lang(ug)::-ms-value, -.win-button.win-button-file:lang(ur)::-ms-value, -.win-button.win-button-file:lang(qps-plocm)::-ms-value { - border-left-style: none; - border-right-style: solid; -} -.win-button.win-button-file::-ms-browse { - margin: 0; - padding: 0 18px; - border-width: 2px; - border-style: solid; - background-clip: padding-box; - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-dropdown { - min-width: 56px; - max-width: 368px; - min-height: 32px; - margin: 8px 0; - border-style: solid; - border-width: 2px; - background-clip: border-box; - background-image: none; - box-sizing: border-box; - border-radius: 0; - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-dropdown::-ms-value { - padding: 5px 12px 7px 12px; - margin: 0; -} -.win-dropdown::-ms-expand { - border: none; - margin-right: 5px; - margin-left: 3px; - margin-bottom: -2px; - font-size: 20px; -} -select[multiple].win-dropdown { - padding: 0 0 0 12px; - vertical-align: bottom; -} -.win-dropdown option { - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-progress-bar, -.win-progress-ring, -.win-ring { - width: 180px; - height: 4px; - -webkit-appearance: none; -} -.win-progress-bar:not(:indeterminate), -.win-progress-ring:not(:indeterminate), -.win-ring:not(:indeterminate) { - border-style: none; -} -.win-progress-bar::-ms-fill, -.win-progress-ring::-ms-fill, -.win-ring::-ms-fill { - border-style: none; -} -.win-progress-bar.win-medium, -.win-progress-ring.win-medium, -.win-ring.win-medium { - width: 296px; -} -.win-progress-bar.win-large, -.win-progress-ring.win-large, -.win-ring.win-large { - width: 100%; -} -.win-progress-bar:indeterminate::-webkit-progress-value, -.win-progress-ring:indeterminate::-webkit-progress-value, -.win-ring:indeterminate::-webkit-progress-value { - position: relative; - -webkit-animation: win-progress-indeterminate 3s linear infinite; -} -.win-progress-bar.win-paused:not(:indeterminate), -.win-progress-ring.win-paused:not(:indeterminate), -.win-ring.win-paused:not(:indeterminate) { - animation-name: win-progress-fade-out; - animation-duration: 3s; - animation-timing-function: cubic-bezier(0.03, 0.76, 0.31, 1); - opacity: 0.5; -} -.win-progress-bar.win-error::-ms-fill, -.win-progress-ring.win-error::-ms-fill, -.win-ring.win-error::-ms-fill { - opacity: 0; -} -.win-progress-ring, -.win-ring { - width: 20px; - height: 20px; -} -.win-progress-ring:indeterminate::-ms-fill, -.win-ring:indeterminate::-ms-fill { - animation-name: -ms-ring; -} -.win-progress-ring.win-medium, -.win-ring.win-medium { - width: 40px; - height: 40px; -} -.win-progress-ring.win-large, -.win-ring.win-large { - width: 60px; - height: 60px; -} -@-webkit-keyframes win-progress-indeterminate { - 0% { - left: 0; - width: 25%; - } - 50% { - left: calc(75%); - width: 25%; - } - 75% { - left: calc(100%); - width: 0%; - } - 75.1% { - left: 0; - width: 0%; - } - 100% { - left: 0; - width: 25%; - } -} -@keyframes win-progress-fade-out { - from { - opacity: 1.0; - } - to { - opacity: 0.5; - } -} -.win-slider { - -webkit-appearance: none; - width: 280px; - height: 22px; - padding-top: 17px; - padding-bottom: 32px; -} -.win-slider::-ms-track { - height: 2px; - border-style: none; -} -.win-slider::-webkit-slider-runnable-track { - height: 2px; - border-style: none; -} -.win-slider::-moz-range-track { - height: 2px; - border-style: none; -} -.win-slider::-ms-thumb { - width: 24px; - height: 8px; - border-radius: 4px; - border-style: none; -} -.win-slider::-webkit-slider-thumb { - -webkit-appearance: none; - margin-top: -4px; - width: 24px; - height: 8px; - border-radius: 4px; - border-style: none; -} -.win-slider::-moz-range-thumb { - width: 24px; - height: 8px; - border-radius: 4px; - border-style: none; -} -.win-slider.win-vertical { - writing-mode: bt-lr; - width: 22px; - height: 280px; -} -.win-slider.win-vertical::-ms-track { - width: 2px; - height: auto; -} -.win-slider.win-vertical::-ms-thumb { - width: 8px; - height: 24px; -} -.win-slider.win-vertical:lang(ar), -.win-slider.win-vertical:lang(dv), -.win-slider.win-vertical:lang(fa), -.win-slider.win-vertical:lang(he), -.win-slider.win-vertical:lang(ku-Arab), -.win-slider.win-vertical:lang(pa-Arab), -.win-slider.win-vertical:lang(prs), -.win-slider.win-vertical:lang(ps), -.win-slider.win-vertical:lang(sd-Arab), -.win-slider.win-vertical:lang(syr), -.win-slider.win-vertical:lang(ug), -.win-slider.win-vertical:lang(ur), -.win-slider.win-vertical:lang(qps-plocm) { - writing-mode: bt-rl; -} -.win-link { - text-decoration: underline; - cursor: pointer; - touch-action: manipulation; -} -.win-code { - font-family: "Consolas", "Menlo", "Monaco", "Courier New", monospace; - font-size: 15px; - font-weight: 400; - line-height: 1.333; -} -.win-type-ellipsis { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -h1.win-type-ellipsis, -.win-type-header.win-type-ellipsis, -.win-h1.win-type-ellipsis { - line-height: 1.4286; -} -h2.win-type-ellipsis, -.win-type-subheader.win-type-ellipsis, -.win-h2.win-type-ellipsis { - line-height: 1.5; -} -.win-scrollview { - overflow-x: auto; - overflow-y: hidden; - height: 400px; - width: 100%; -} -h1.win-type-header, -h2.win-type-subheader, -h3.win-type-title, -h4.win-type-subtitle, -h5.win-type-base, -h6.win-type-body, -h1.win-h1, -h2.win-h2, -h3.win-h3, -h4.win-h4, -h5.win-h5, -h6.win-h6 { - margin-top: 0px; - margin-bottom: 0px; -} -.win-type-body p, -p.win-type-body { - font-weight: 300; -} -.win-listview { - overflow: hidden; - height: 400px; -} -.win-listview .win-surface { - overflow: visible; -} -.win-listview > .win-viewport.win-horizontal .win-surface { - height: 100%; -} -.win-listview > .win-viewport.win-vertical .win-surface { - width: 100%; -} -.win-listview > .win-viewport { - position: relative; - width: 100%; - height: 100%; - z-index: 0; - -ms-overflow-style: -ms-autohiding-scrollbar; - -webkit-overflow-scrolling: touch; - white-space: nowrap; -} -.win-listview > .win-viewport.win-horizontal { - overflow-x: auto; - overflow-y: hidden; -} -.win-listview > .win-viewport.win-vertical { - overflow-x: hidden; - overflow-y: auto; -} -.win-listview .win-itemscontainer { - overflow: hidden; -} -.win-listview .win-itemscontainer-padder { - width: 0; - height: 0; - margin: 0; - padding: 0; - border: 0; - overflow: hidden; -} -.win-listview > .win-horizontal .win-container { - margin: 10px 5px 0px 5px; -} -.win-listview > .win-vertical .win-container { - margin: 10px 24px 0px 7px; -} -.win-listview.win-rtl > .win-vertical .win-container { - margin: 10px 7px 0px 24px; -} -.win-listview .win-container, -.win-listview .win-itembox, -.win-itemcontainer.win-container, -.win-itemcontainer .win-itembox { - cursor: default; - z-index: 0; -} -.win-listview .win-container { - touch-action: pan-x pan-y pinch-zoom; -} -.win-semanticzoom .win-listview > .win-viewport * { - touch-action: auto; -} -.win-semanticzoom .win-listview > .win-viewport.win-zooming-x { - overflow-x: visible; -} -.win-semanticzoom .win-listview > .win-viewport.win-zooming-y { - overflow-y: visible; -} -.win-listview .win-itembox, -.win-itemcontainer .win-itembox { - width: 100%; - height: 100%; -} -.win-listview .win-item, -.win-itemcontainer .win-item { - z-index: 1; -} -.win-listview .win-item, -.win-itemcontainer .win-item { - overflow: hidden; - position: relative; -} -.win-listview > .win-vertical .win-item { - width: 100%; -} -.win-listview .win-item:focus, -.win-itemcontainer .win-item:focus { - outline-style: none; -} -.win-listview .win-focusedoutline, -.win-itemcontainer .win-focusedoutline { - width: calc(100% - 4px); - height: calc(100% - 4px); - left: 2px; - top: 2px; - position: absolute; - z-index: 5; - pointer-events: none; -} -.win-container.win-selected .win-selectionborder { - border-width: 2px; - border-style: solid; -} -html.win-hoverable .win-container.win-selected:hover .win-selectionborder { - border-width: 2px; - border-style: solid; -} -html.win-hoverable .win-listview .win-itembox:hover::before, -html.win-hoverable .win-itemcontainer .win-itembox:hover::before { - position: absolute; - left: 0px; - top: 0px; - content: ""; - width: calc(100% - 4px); - height: calc(100% - 4px); - pointer-events: none; - border-style: solid; - border-width: 2px; - z-index: 3; -} -html.win-hoverable .win-listview.win-selectionstylefilled .win-itembox:hover::before, -html.win-hoverable .win-itemcontainer.win-selectionstylefilled .win-itembox:hover::before, -html.win-hoverable .win-listview .win-itembox.win-selected:hover::before, -html.win-hoverable .win-itemcontainer.win-itembox.win-selected:hover::before, -html.win-hoverable .win-itemcontainer.win-itembox.win-selected:hover::before { - display: none; -} -.win-listview .win-groupheader { - padding: 10px 10px 10px 2px; - overflow: hidden; - outline-width: 0.01px; - outline-style: none; - float: left; - font-size: 34px; - font-weight: 200; - line-height: 1.176; -} -.win-listview .win-groupheadercontainer { - z-index: 1; - touch-action: pan-x pan-y pinch-zoom; - overflow: hidden; -} -.win-listview .win-horizontal .win-headercontainer, -.win-listview .win-horizontal .win-footercontainer { - height: 100%; - display: inline-block; - overflow: hidden; - white-space: normal; -} -.win-listview .win-vertical .win-headercontainer, -.win-listview .win-vertical .win-footercontainer { - width: 100%; - display: block; - overflow: hidden; - white-space: normal; -} -.win-listview .win-groupheader.win-focused { - outline-style: dotted; -} -.win-listview.win-rtl .win-groupheader { - padding-left: 10px; - padding-right: 2px; - float: right; -} -.win-listview.win-groups .win-horizontal .win-groupleader { - margin-left: 70px; -} -.win-listview.win-groups.win-rtl .win-horizontal .win-groupleader { - margin-left: 0; - margin-right: 70px; -} -.win-listview.win-groups .win-vertical .win-listlayout .win-groupleader, -.win-listview.win-groups .win-vertical .win-gridlayout .win-groupleader { - margin-top: 70px; -} -.win-listview.win-groups > .win-vertical .win-surface.win-listlayout, -.win-listview.win-groups > .win-vertical .win-surface.win-gridlayout { - margin-top: -65px; -} -.win-listview.win-groups > .win-horizontal .win-surface { - margin-left: -70px; -} -.win-listview.win-groups.win-rtl > .win-horizontal .win-surface { - margin-left: 0; - margin-right: -70px; -} -.win-listview .win-surface { - -webkit-margin-collapse: separate; - white-space: normal; -} -.win-surface ._win-proxy { - position: relative; - overflow: hidden; - width: 0; - height: 0; - touch-action: none; -} -.win-selectionborder { - position: absolute; - opacity: inherit; - z-index: 2; - pointer-events: none; -} -.win-container.win-selected .win-selectionborder { - top: 0; - left: 0; - right: 0; - bottom: 0; -} -.win-selectionbackground { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - z-index: 0; -} -.win-selectioncheckmarkbackground { - position: absolute; - top: 2px; - right: 2px; - width: 14px; - height: 11px; - margin: 0; - padding: 0; - border-left-width: 2px; - border-right-width: 2px; - border-top-width: 4px; - border-bottom-width: 3px; - border-style: solid; - z-index: 3; - display: none; -} -.win-listview.win-rtl .win-selectioncheckmarkbackground, -.win-itemcontainer.win-rtl .win-selectioncheckmarkbackground { - left: 2px; - right: auto; -} -.win-selectionmode.win-itemcontainer .win-selectioncheckmarkbackground, -.win-selectionmode.win-itemcontainer.win-selectionmode .win-selectioncheckmark, -.win-selectionmode .win-itemcontainer .win-selectioncheckmarkbackground, -.win-selectionmode .win-itemcontainer.win-selectionmode .win-selectioncheckmark, -.win-listview .win-selectionmode .win-selectioncheckmarkbackground, -.win-listview .win-selectionmode .win-selectioncheckmark { - display: block; -} -.win-selectioncheckmark { - position: absolute; - margin: 0; - padding: 2px; - right: 1px; - top: 1px; - font-family: "Segoe MDL2 Assets", "Symbols"; - font-size: 14px; - z-index: 4; - line-height: 1; - display: none; -} -.win-rtl .win-selectioncheckmark { - right: auto; - left: 0px; -} -.win-selectionstylefilled.win-container, -.win-selectionstylefilled .win-container { - overflow: hidden; -} -.win-selectionmode .win-itemcontainer.win-container .win-itembox::after, -.win-selectionmode.win-itemcontainer.win-container .win-itembox::after, -.win-listview .win-surface.win-selectionmode .win-itembox::after { - content: ""; - position: absolute; - width: 18px; - height: 18px; - pointer-events: none; - right: 2px; - top: 2px; - z-index: 3; -} -.win-rtl .win-selectionmode .win-itemcontainer.win-container .win-itembox::after, -.win-itemcontainer.win-rtl.win-selectionmode.win-container .win-itembox::after, -.win-listview.win-rtl .win-surface.win-selectionmode .win-itembox::after { - right: auto; - left: 2px; -} -.win-listview.win-selectionstylefilled .win-surface.win-selectionmode .win-item { - transition: transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - -webkit-transition: -webkit-transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - transform: translate(40px, 0px); - -webkit-transform: translate(40px, 0px); -} -.win-listview.win-rtl.win-selectionstylefilled .win-surface.win-selectionmode .win-item { - transition: transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - -webkit-transition: -webkit-transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - transform: translate(-40px, 0px); - -webkit-transform: translate(-40px, 0px); -} -.win-listview.win-selectionstylefilled .win-surface.win-hidingselectionmode .win-item { - transition: transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - -webkit-transition: -webkit-transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - transform: none; - -webkit-transform: none; -} -.win-listview.win-rtl.win-selectionstylefilled .win-surface.win-hideselectionmode .win-item { - transition: transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - -webkit-transition: -webkit-transform 250ms cubic-bezier(0.17, 0.79, 0.215, 1.0025); - transform: none; - -webkit-transform: none; -} -.win-listview.win-selectionstylefilled .win-surface.win-selectionmode .win-itembox::after { - left: 12px; - right: auto; - top: 50%; - margin-top: -9px; - display: block; - border: 2px solid; - width: 16px; - height: 16px; -} -.win-listview.win-selectionstylefilled.win-rtl .win-surface.win-selectionmode .win-itembox::after { - left: auto; - right: 12px; -} -.win-listview.win-selectionstylefilled .win-surface.win-selectionmode .win-selectioncheckmarkbackground { - left: 12px; - top: 50%; - margin-top: -9px; - display: block; - border: 2px solid; - width: 16px; - height: 16px; -} -.win-listview.win-selectionstylefilled.win-rtl .win-surface.win-selectionmode .win-selectioncheckmarkbackground { - left: auto; - right: 12px; -} -.win-listview.win-selectionstylefilled .win-surface.win-selectionmode .win-selectioncheckmark { - left: 13px; - top: 50%; - margin-top: -8px; - display: block; - width: 14px; - height: 14px; -} -.win-listview.win-selectionstylefilled.win-rtl .win-surface.win-selectionmode .win-selectioncheckmark { - left: 0; - right: 10px; -} -.win-selectionmode .win-itemcontainer.win-selectionstylefilled.win-container .win-itembox.win-selected::after, -.win-itemcontainer.win-selectionmode.win-selectionstylefilled.win-container .win-itembox.win-selected::after, -.win-listview.win-selectionstylefilled .win-surface.win-selectionmode .win-itembox.win-nonselectable::after, -.win-listview .win-surface.win-selectionmode .win-itembox.win-selected::after { - display: none; -} -.win-listview .win-progress { - left: 50%; - top: 50%; - width: 60px; - height: 60px; - margin-left: -30px; - margin-top: -30px; - z-index: 1; - position: absolute; -} -.win-listview .win-progress::-ms-fill { - animation-name: -ms-ring; -} -.win-listview .win-itemsblock { - overflow: hidden; -} -.win-listview .win-surface.win-nocssgrid.win-gridlayout, -.win-listview .win-horizontal .win-nocssgrid.win-listlayout, -.win-listview .win-vertical .win-nocssgrid.win-listlayout.win-headerpositionleft { - display: -ms-inline-flexbox; - display: -webkit-inline-flex; - display: inline-flex; - vertical-align: top; -} -.win-listview .win-horizontal .win-surface.win-nocssgrid { - -ms-flex-direction: column; - -webkit-flex-direction: column; - flex-direction: column; - -ms-flex-wrap: wrap; - -webkit-flex-wrap: wrap; - flex-wrap: wrap; - -ms-flex-line-pack: start; - -webkit-align-content: flex-start; - align-content: flex-start; -} -.win-listview .win-vertical .win-surface.win-nocssgrid { - -ms-flex-direction: row; - -webkit-flex-direction: row; - flex-direction: row; - -ms-flex-wrap: wrap; - -webkit-flex-wrap: wrap; - flex-wrap: wrap; - -ms-flex-line-pack: start; - -webkit-align-content: flex-start; - align-content: flex-start; -} -.win-listview .win-vertical .win-structuralnodes.win-single-itemsblock.win-listlayout .win-itemscontainer.win-laidout, -.win-listview .win-horizontal .win-structuralnodes.win-single-itemsblock.win-listlayout .win-itemscontainer.win-laidout, -.win-listview .win-vertical .win-structuralnodes.win-single-itemsblock.win-gridlayout .win-uniformgridlayout.win-itemscontainer.win-laidout, -.win-listview .win-horizontal .win-structuralnodes.win-single-itemsblock.win-gridlayout .win-uniformgridlayout.win-itemscontainer.win-laidout { - display: block; -} -.win-listview .win-vertical .win-structuralnodes.win-single-itemsblock.win-listlayout .win-itemscontainer.win-laidout .win-itemscontainer-padder, -.win-listview .win-horizontal .win-structuralnodes.win-single-itemsblock.win-listlayout .win-itemscontainer.win-laidout .win-itemscontainer-padder, -.win-listview .win-vertical .win-structuralnodes.win-single-itemsblock.win-gridlayout .win-uniformgridlayout.win-itemscontainer.win-laidout .win-itemscontainer-padder, -.win-listview .win-horizontal .win-structuralnodes.win-single-itemsblock.win-gridlayout .win-uniformgridlayout.win-itemscontainer.win-laidout .win-itemscontainer-padder { - height: 0; - width: 0; -} -.win-listview.win-groups .win-vertical .win-listlayout.win-headerpositionleft .win-itemscontainer, -.win-listview.win-groups .win-vertical .win-listlayout.win-headerpositionleft .win-groupheadercontainer, -.win-listview.win-groups .win-horizontal .win-listlayout .win-itemscontainer, -.win-listview.win-groups .win-horizontal .win-listlayout .win-groupheadercontainer { - display: none; -} -.win-listview.win-groups .win-vertical .win-listlayout.win-headerpositionleft .win-itemscontainer.win-laidout, -.win-listview.win-groups .win-vertical .win-listlayout.win-headerpositionleft .win-groupheadercontainer.win-laidout, -.win-listview.win-groups .win-horizontal .win-listlayout .win-groupheadercontainer.win-laidout { - display: block; -} -.win-listview .win-listlayout .win-itemscontainer { - overflow: visible; -} -.win-listview .win-listlayout .win-itemsblock { - padding-bottom: 4px; - margin-bottom: -4px; -} -.win-listview > .win-vertical .win-listlayout.win-headerpositiontop .win-groupheader { - float: none; -} -.win-listview > .win-vertical .win-surface.win-listlayout { - margin-bottom: 5px; -} -.win-listview .win-vertical .win-listlayout.win-headerpositionleft.win-surface { - display: -ms-inline-grid; - -ms-grid-columns: auto 1fr; - -ms-grid-rows: auto; -} -.win-listview .win-vertical .win-listlayout.win-headerpositionleft .win-groupheadercontainer { - -ms-grid-column: 1; -} -.win-listview .win-vertical .win-listlayout.win-headerpositionleft .win-itemscontainer { - -ms-grid-column: 2; -} -.win-listview > .win-horizontal .win-surface.win-listlayout { - display: -ms-inline-grid; - -ms-grid-columns: auto; - -ms-grid-rows: auto; - vertical-align: top; -} -.win-listview .win-horizontal .win-listlayout .win-itemsblock { - height: 100%; -} -.win-listview .win-horizontal .win-listlayout .win-itemscontainer { - margin-bottom: 24px; -} -.win-listview .win-horizontal .win-listlayout .win-container { - height: calc(100% - 10px); -} -.win-listview > .win-horizontal .win-surface.win-listlayout.win-headerpositiontop { - -ms-grid-rows: auto 1fr; -} -.win-listview .win-horizontal .win-listlayout.win-headerpositiontop .win-groupheadercontainer { - -ms-grid-row: 1; -} -.win-listview .win-horizontal .win-listlayout.win-headerpositiontop .win-itemscontainer { - -ms-grid-row: 2; -} -.win-listview .win-gridlayout.win-surface { - display: -ms-inline-grid; - vertical-align: top; -} -.win-listview .win-gridlayout .win-container { - margin: 5px; -} -.win-listview .win-vertical .win-gridlayout.win-headerpositionleft .win-groupheadercontainer, -.win-listview .win-vertical .win-gridlayout.win-headerpositiontop .win-groupheadercontainer { - -ms-grid-column: 1; -} -.win-listview.win-groups .win-gridlayout .win-itemscontainer, -.win-listview.win-groups .win-gridlayout .win-groupheadercontainer { - display: none; -} -.win-listview.win-groups .win-gridlayout .win-groupheadercontainer.win-laidout { - display: block; -} -.win-listview .win-horizontal .win-gridlayout.win-headerpositiontop.win-surface { - -ms-grid-columns: auto; - -ms-grid-rows: auto 1fr; -} -.win-listview .win-horizontal .win-gridlayout.win-headerpositiontop .win-groupheadercontainer { - -ms-grid-row: 1; -} -.win-listview .win-horizontal .win-gridlayout.win-headerpositiontop .win-itemscontainer { - -ms-grid-row: 2; -} -.win-listview .win-horizontal .win-gridlayout.win-headerpositionleft.win-surface { - -ms-grid-columns: auto; - -ms-grid-rows: auto; -} -.win-listview .win-horizontal .win-gridlayout.win-headerpositionleft .win-groupheadercontainer { - -ms-grid-row: 1; -} -.win-listview .win-horizontal .win-gridlayout.win-headerpositionleft .win-itemscontainer { - -ms-grid-row: 1; -} -.win-listview .win-vertical .win-gridlayout.win-headerpositiontop.win-surface { - -ms-grid-columns: auto; - -ms-grid-rows: auto; -} -.win-listview .win-vertical .win-gridlayout.win-headerpositiontop .win-itemscontainer { - -ms-grid-column: 1; -} -.win-listview .win-vertical .win-gridlayout.win-headerpositionleft.win-surface { - -ms-grid-columns: auto 1fr; - -ms-grid-rows: auto; -} -.win-listview .win-vertical .win-gridlayout.win-headerpositionleft .win-itemscontainer { - -ms-grid-column: 2; -} -.win-listview .win-gridlayout.win-structuralnodes .win-uniformgridlayout.win-itemscontainer.win-laidout { - display: -ms-flexbox; - display: -webkit-flex; - display: flex; - -ms-flex-direction: row; - -webkit-flex-direction: row; - flex-direction: row; -} -.win-listview .win-horizontal .win-listlayout .win-itemscontainer, -.win-listview.win-groups .win-horizontal .win-listlayout .win-itemscontainer.win-laidout, -.win-listview .win-horizontal .win-listlayout .win-itemsblock, -.win-listview .win-horizontal .win-gridlayout .win-uniformgridlayout.win-itemscontainer.win-laidout, -.win-listview .win-horizontal .win-gridlayout .win-uniformgridlayout .win-itemsblock { - display: -ms-flexbox; - display: -webkit-flex; - display: flex; - -ms-flex-direction: column; - -webkit-flex-direction: column; - flex-direction: column; - -ms-flex-wrap: wrap; - -webkit-flex-wrap: wrap; - flex-wrap: wrap; - -ms-flex-line-pack: start; - -webkit-align-content: flex-start; - align-content: flex-start; -} -.win-listview .win-horizontal .win-itemscontainer-padder { - height: 100%; -} -.win-listview .win-horizontal .win-gridlayout .win-uniformgridlayout .win-itemsblock { - height: 100%; -} -.win-listview .win-horizontal .win-gridlayout .win-cellspanninggridlayout.win-itemscontainer.win-laidout { - display: -ms-grid; -} -.win-listview .win-vertical .win-gridlayout.win-structuralnodes .win-uniformgridlayout.win-itemscontainer.win-laidout { - display: -ms-flexbox; - display: -webkit-flex; - display: flex; - -ms-flex-direction: column; - -webkit-flex-direction: column; - flex-direction: column; -} -.win-listview .win-vertical .win-gridlayout .win-uniformgridlayout.win-itemscontainer.win-laidout, -.win-listview .win-vertical .win-gridlayout .win-uniformgridlayout .win-itemsblock { - display: -ms-flexbox; - display: -webkit-flex; - display: flex; - -ms-flex-direction: row; - -webkit-flex-direction: row; - flex-direction: row; - -ms-flex-wrap: wrap; - -webkit-flex-wrap: wrap; - flex-wrap: wrap; - -ms-flex-line-pack: start; - -webkit-align-content: flex-start; - align-content: flex-start; -} -.win-listview .win-vertical .win-gridlayout .win-uniformgridlayout .win-itemsblock { - width: 100%; -} -.win-listview .win-cellspanninggridlayout .win-container.win-laidout { - display: block; -} -.win-listview .win-cellspanninggridlayout .win-container { - display: none; -} -.win-listview .win-itembox { - position: relative; -} -.win-listview.win-dragover .win-itembox { - transform: scale(0.86); - -webkit-transform: scale(0.86); -} -.win-listview .win-itembox.win-dragsource, -.win-itemcontainer .win-itembox.win-dragsource { - opacity: 0.5; - transition: opacity cubic-bezier(0.1, 0.9, 0.2, 1) 167ms, transform cubic-bezier(0.1, 0.9, 0.2, 1) 220ms; - -webkit-transition: opacity cubic-bezier(0.1, 0.9, 0.2, 1) 167ms, transform cubic-bezier(0.1, 0.9, 0.2, 1) 220ms; -} -.win-listview.win-dragover .win-itembox.win-dragsource { - opacity: 0; - transition: none; - -webkit-transition: none; -} -html.win-hoverable .win-listview.win-dragover .win-container:hover { - outline: none; -} -.win-listview .win-itembox { - transition: transform cubic-bezier(0.1, 0.9, 0.2, 1) 220ms; - -webkit-transition: -webkit-transform cubic-bezier(0.1, 0.9, 0.2, 1) 220ms; -} -.win-listview.win-groups > .win-vertical .win-surface.win-listlayout.win-headerpositionleft { - margin-left: 70px; -} -.win-listview.win-groups.win-rtl > .win-vertical .win-surface.win-listlayout.win-headerpositionleft { - margin-left: 0px; - margin-right: 70px; -} -.win-listview > .win-horizontal .win-surface.win-listlayout { - margin-left: 70px; -} -.win-listview.win-rtl > .win-horizontal .win-surface.win-listlayout { - margin-left: 0px; - margin-right: 70px; -} -.win-listview .win-vertical .win-gridlayout.win-surface { - margin-left: 20px; -} -.win-listview.win-rtl .win-vertical .win-gridlayout.win-surface { - margin-left: 0px; - margin-right: 20px; -} -.win-itemcontainer .win-itembox, -.win-itemcontainer.win-container { - position: relative; -} -.win-itemcontainer { - touch-action: pan-x pan-y pinch-zoom; -} -html.win-hoverable .win-listview .win-itembox:hover::before, -html.win-hoverable .win-itemcontainer .win-itembox:hover::before { - opacity: 0.4; -} -html.win-hoverable .win-listview .win-pressed .win-itembox:hover::before, -html.win-hoverable .win-itemcontainer .win-pressed .win-itembox:hover::before, -html.win-hoverable .win-listview .win-pressed.win-itembox:hover::before, -html.win-hoverable .win-itemcontainer .win-pressed.win-itembox:hover::before { - opacity: 0.6; -} -html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover, -html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover, -html.win-hoverable .win-selectionstylefilled .win-itemcontainer.win-container:hover { - outline: none; -} -.win-selectionstylefilled.win-itemcontainer .win-itembox, -.win-selectionstylefilled .win-itemcontainer .win-itembox, -.win-listview.win-selectionstylefilled .win-itembox { - background-color: transparent; -} -.win-listview.win-selectionstylefilled .win-container.win-selected .win-selectionborder, -.win-itemcontainer.win-selectionstylefilled.win-container.win-selected .win-selectionborder { - border-color: transparent; -} -.win-listview.win-selectionstylefilled .win-surface.win-selectionmode .win-itembox::after { - background-color: transparent; -} -.win-listview.win-selectionstylefilled .win-selectioncheckmarkbackground, -.win-itemcontainer.win-selectionstylefilled .win-selectioncheckmarkbackground { - border-color: transparent; -} -.win-listview.win-selectionstylefilled .win-selected a, -.win-listview.win-selectionstylefilled .win-selected progress, -.win-listview.win-selectionstylefilled .win-selected .win-rating .win-star.win-full, -.win-itemcontainer.win-selectionstylefilled.win-selected a, -.win-itemcontainer.win-selectionstylefilled.win-selected progress, -.win-itemcontainer.win-selectionstylefilled.win-selected .win-rating .win-star.win-full { - color: #ffffff; -} -.win-listview.win-selectionstylefilled .win-selected.win-selected a:hover:active, -.win-itemcontainer.win-selectionstylefilled.win-selected.win-selected a:hover:active { - color: rgba(255, 255, 255, 0.6); -} -html.win-hoverable .win-listview.win-selectionstylefilled .win-selected a:hover, -html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-selected a:hover { - color: rgba(255, 255, 255, 0.8); -} -.win-listview.win-selectionstylefilled .win-selected button, -.win-listview.win-selectionstylefilled .win-selected input[type=button], -.win-listview.win-selectionstylefilled .win-selected input[type=reset], -.win-listview.win-selectionstylefilled .win-selected input[type=text], -.win-listview.win-selectionstylefilled .win-selected input[type=password], -.win-listview.win-selectionstylefilled .win-selected input[type=email], -.win-listview.win-selectionstylefilled .win-selected input[type=number], -.win-listview.win-selectionstylefilled .win-selected input[type=tel], -.win-listview.win-selectionstylefilled .win-selected input[type=url], -.win-listview.win-selectionstylefilled .win-selected input[type=search], -.win-listview.win-selectionstylefilled .win-selected input::-ms-check, -.win-listview.win-selectionstylefilled .win-selected textarea, -.win-listview.win-selectionstylefilled .win-selected .win-textarea, -.win-listview.win-selectionstylefilled .win-selected select, -.win-itemcontainer.win-selectionstylefilled.win-selected button, -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=button], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=reset], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=text], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=password], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=email], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=number], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=tel], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=url], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=search], -.win-itemcontainer.win-selectionstylefilled.win-selected input::-ms-check, -.win-itemcontainer.win-selectionstylefilled.win-selected textarea, -.win-itemcontainer.win-selectionstylefilled.win-selected .win-textarea, -.win-itemcontainer.win-selectionstylefilled.win-selected select { - background-clip: border-box; - background-color: rgba(255, 255, 255, 0.8); - border-color: transparent; - color: #000000; -} -.win-listview.win-selectionstylefilled .win-selected button[type=submit], -.win-listview.win-selectionstylefilled .win-selected input[type=submit], -.win-itemcontainer.win-selectionstylefilled.win-selected button[type=submit], -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=submit] { - border-color: #ffffff; -} -.win-listview.win-selectionstylefilled .win-selected input[type=range]::-ms-fill-lower, -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=range]::-ms-fill-lower { - background-color: #ffffff; -} -.win-listview.win-selectionstylefilled .win-selected input[type=range]::-ms-thumb, -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=range]::-ms-thumb { - background-color: #000000; -} -.win-listview.win-selectionstylefilled .win-selected input[type=range]::-ms-fill-upper, -.win-listview.win-selectionstylefilled .win-selected progress, -.win-itemcontainer.win-selectionstylefilled.win-selected input[type=range]::-ms-fill-upper, -.win-itemcontainer.win-selectionstylefilled.win-selected progress { - background-color: rgba(255, 255, 255, 0.16); -} -.win-listview.win-selectionstylefilled .win-selected progress:indeterminate, -.win-itemcontainer.win-selectionstylefilled.win-selected progress:indeterminate { - background-color: transparent; -} -.win-listview.win-selectionstylefilled .win-selected .win-rating .win-star.win-empty, -.win-itemcontainer.win-selectionstylefilled.win-selected .win-rating .win-star.win-empty { - color: rgba(255, 255, 255, 0.16); -} -.win-listview .win-viewport { - outline: none; -} -@media (-ms-high-contrast) { - .win-listview .win-groupheader { - color: WindowText; - } - .win-selectioncheckmark { - color: HighlightText; - } - .win-listview .win-focusedoutline, - .win-listview .win-groupheader, - .win-itemcontainer .win-focusedoutline { - outline-color: WindowText; - } - .win-listview.win-selectionstylefilled .win-itembox, - .win-itemcontainer.win-selectionstylefilled .win-itembox { - background-color: Window; - color: WindowText; - } - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover .win-itembox, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover .win-itembox { - background-color: Highlight; - color: HighlightText; - } - .win-listview.win-selectionstylefilled .win-container.win-selected .win-itembox, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container.win-selected:hover .win-itembox, - .win-itemcontainer.win-selectionstylefilled.win-container.win-selected .win-itembox, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container.win-selected:hover .win-itembox { - background-color: Highlight; - color: HighlightText; - } - .win-listview:not(.win-selectionstylefilled) .win-container.win-selected .win-selectionborder, - .win-itemcontainer:not(.win-selectionstylefilled).win-container.win-selected .win-selectionborder { - border-color: Highlight; - } - .win-listview.win-selectionstylefilled .win-container.win-selected .win-selectionborder, - .win-itemcontainer.win-selectionstylefilled.win-container.win-selected .win-selectionborder { - border-color: transparent; - } - html.win-hoverable .win-listview:not(.win-selectionstylefilled) .win-container.win-selected:hover .win-selectionborder, - html.win-hoverable .win-itemcontainer:not(.win-selectionstylefilled).win-container.win-selected:hover .win-selectionborder { - border-color: Highlight; - } - .win-listview.win-selectionstylefilled .win-selected .win-selectionbackground, - html.win-hoverable .win-listview.win-selectionstylefilled .win-selected:hover .win-selectionbackground, - .win-itemcontainer.win-selectionstylefilled.win-selected .win-selectionbackground, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-selected:hover .win-selectionbackground { - background-color: Highlight; - color: HighlightText; - } - .win-listview.win-selectionstylefilled .win-selectioncheckmarkbackground, - .win-itemcontainer.win-selectionstylefilled .win-selectioncheckmarkbackground { - border-color: transparent; - } - .win-listview.win-selectionstylefilled .win-selected a, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover a, - .win-listview.win-selectionstylefilled .win-selected progress, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover progress, - .win-listview.win-selectionstylefilled .win-selected .win-rating .win-star:after, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover .win-rating .win-star:after, - .win-itemcontainer.win-selectionstylefilled.win-selected a, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover a, - .win-itemcontainer.win-selectionstylefilled.win-selected progress, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover progress, - .win-itemcontainer.win-selectionstylefilled.win-selected .win-rating .win-star:after, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover .win-rating .win-star:after { - color: HighlightText; - } - .win-listview.win-selectionstylefilled .win-selected input, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover input, - .win-listview.win-selectionstylefilled .win-selected input::-ms-check, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover input::-ms-check, - .win-listview.win-selectionstylefilled .win-selected input::-ms-value, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover input::-ms-value, - .win-listview.win-selectionstylefilled .win-selected input::-ms-track, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover input::-ms-track, - .win-listview.win-selectionstylefilled .win-selected button, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover button, - .win-listview.win-selectionstylefilled .win-selected progress, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover progress, - .win-listview.win-selectionstylefilled .win-selected progress::-ms-fill, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover progress::-ms-fill, - .win-listview.win-selectionstylefilled .win-selected select, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover select, - .win-listview.win-selectionstylefilled .win-selected textarea, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover textarea, - .win-listview.win-selectionstylefilled.win-selected input, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover input, - .win-itemcontainer.win-selectionstylefilled.win-selected input::-ms-check, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover input::-ms-check, - .win-itemcontainer.win-selectionstylefilled.win-selected input::-ms-value, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover input::-ms-value, - .win-itemcontainer.win-selectionstylefilled.win-selected input::-ms-track, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover input::-ms-track, - .win-itemcontainer.win-selectionstylefilled.win-selected button, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover button, - .win-itemcontainer.win-selectionstylefilled.win-selected progress, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover progress, - .win-itemcontainer.win-selectionstylefilled.win-selected progress::-ms-fill, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover progress::-ms-fill, - .win-itemcontainer.win-selectionstylefilled.win-selected select, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover select, - .win-itemcontainer.win-selectionstylefilled.win-selected textarea, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover textarea { - border-color: HighlightText; - } - .win-listview.win-selectionstylefilled .win-selected input[type=range]::-ms-fill-lower, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover input[type=range]::-ms-fill-lower, - .win-listview.win-selectionstylefilled .win-selected progress::-ms-fill, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover progress::-ms-fill, - .win-itemcontainer.win-selectionstylefilled.win-selected input[type=range]::-ms-fill-lower, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover input[type=range]::-ms-fill-lower, - .win-itemcontainer.win-selectionstylefilled.win-selected progress::-ms-fill, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover progress::-ms-fill { - background-color: HighlightText; - } - .win-listview.win-selectionstylefilled .win-selected input[type=range]::-ms-fill-upper, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover input[type=range]::-ms-fill-upper, - .win-listview.win-selectionstylefilled .win-selected progress, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover progress, - .win-itemcontainer.win-selectionstylefilled.win-selected input[type=range]::-ms-fill-upper, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover input[type=range]::-ms-fill-upper, - .win-itemcontainer.win-selectionstylefilled.win-selected progress, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover progress { - background-color: Highlight; - } - .win-listview.win-selectionstylefilled .win-selected .win-rating .win-star.win-full:before, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover .win-rating .win-star.win-full:before, - .win-itemcontainer.win-selectionstylefilled.win-selected .win-rating .win-star.win-full:before, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover .win-rating .win-star.win-full:before { - color: ButtonFace; - } - .win-listview.win-selectionstylefilled .win-selected .win-rating .win-star.win-empty:before, - html.win-hoverable .win-listview.win-selectionstylefilled .win-container:hover .win-rating .win-star.win-empty:before, - .win-itemcontainer.win-selectionstylefilled.win-selected .win-rating .win-star.win-empty:before, - html.win-hoverable .win-itemcontainer.win-selectionstylefilled.win-container:hover .win-rating .win-star.win-empty:before { - color: Highlight; - } - html.win-hoverable .win-listview .win-container:hover, - html.win-hoverable .win-itemcontainer.win-container:hover { - outline: Highlight solid 3px; - } -} -.win-flipview { - overflow: hidden; - height: 400px; -} -.win-flipview .win-surface { - -ms-scroll-chaining: none; -} -.win-flipview .win-navleft { - left: 0%; - top: 50%; - margin-top: -19px; -} -.win-flipview .win-navright { - left: 100%; - top: 50%; - margin-left: -20px; - margin-top: -19px; -} -.win-flipview .win-navtop { - left: 50%; - top: 0%; - margin-left: -35px; -} -.win-flipview .win-navbottom { - left: 50%; - top: 100%; - margin-left: -35px; - margin-top: -36px; -} -.win-flipview .win-navbutton { - touch-action: manipulation; - border: none; - width: 20px; - height: 36px; - z-index: 1; - position: absolute; - font-family: "Segoe MDL2 Assets", "Symbols"; - font-size: 16px; - padding: 0; - min-width: 0; -} -.win-flipview .win-item, -.win-flipview .win-item > .win-template { - height: 100%; - width: 100%; - display: -ms-flexbox; - display: -webkit-flex; - display: flex; - -ms-flex-align: center; - -webkit-align-items: center; - align-items: center; - -ms-flex-pack: center; - -webkit-justify-content: center; - justify-content: center; -} -@media (-ms-high-contrast) { - .win-flipview .win-navbottom { - left: 50%; - top: 100%; - margin-left: -35px; - margin-top: -35px; - } - .win-flipview .win-navbutton { - background-color: ButtonFace; - color: ButtonText; - border: 2px solid ButtonText; - width: 65px; - height: 35px; - } - .win-flipview .win-navbutton.win-navbutton:hover:active, - .win-flipview .win-navbutton.win-navbutton:active { - background-color: ButtonText; - color: ButtonFace; - } - .win-flipview .win-navright { - margin-left: -65px; - } - html.win-hoverable .win-flipview .win-navbutton:hover { - background-color: Highlight; - color: HighlightText; - } -} -.win-datepicker { - display: -ms-inline-flexbox; - display: -webkit-inline-flex; - display: inline-flex; - height: auto; - width: auto; -} -.win-datepicker select { - min-width: 80px; - margin-top: 4px; - margin-bottom: 4px; -} -.win-datepicker .win-datepicker-month { - margin-right: 20px; -} -.win-datepicker .win-datepicker-date.win-order0, -.win-datepicker .win-datepicker-date.win-order1 { - margin-right: 20px; -} -.win-datepicker .win-datepicker-year.win-order0 { - margin-right: 20px; -} -.win-datepicker .win-datepicker-month:lang(ar), -.win-datepicker .win-datepicker-month:lang(dv), -.win-datepicker .win-datepicker-month:lang(fa), -.win-datepicker .win-datepicker-month:lang(he), -.win-datepicker .win-datepicker-month:lang(ku-Arab), -.win-datepicker .win-datepicker-month:lang(pa-Arab), -.win-datepicker .win-datepicker-month:lang(prs), -.win-datepicker .win-datepicker-month:lang(ps), -.win-datepicker .win-datepicker-month:lang(sd-Arab), -.win-datepicker .win-datepicker-month:lang(syr), -.win-datepicker .win-datepicker-month:lang(ug), -.win-datepicker .win-datepicker-month:lang(ur), -.win-datepicker .win-datepicker-month:lang(qps-plocm), -.win-datepicker .win-datepicker-date.win-order0:lang(ar), -.win-datepicker .win-datepicker-date.win-order0:lang(dv), -.win-datepicker .win-datepicker-date.win-order0:lang(fa), -.win-datepicker .win-datepicker-date.win-order0:lang(he), -.win-datepicker .win-datepicker-date.win-order0:lang(ku-Arab), -.win-datepicker .win-datepicker-date.win-order0:lang(pa-Arab), -.win-datepicker .win-datepicker-date.win-order0:lang(prs), -.win-datepicker .win-datepicker-date.win-order0:lang(ps), -.win-datepicker .win-datepicker-date.win-order0:lang(sd-Arab), -.win-datepicker .win-datepicker-date.win-order0:lang(syr), -.win-datepicker .win-datepicker-date.win-order0:lang(ug), -.win-datepicker .win-datepicker-date.win-order0:lang(ur), -.win-datepicker .win-datepicker-date.win-order0:lang(qps-plocm), -.win-datepicker .win-datepicker-date.win-order1:lang(ar), -.win-datepicker .win-datepicker-date.win-order1:lang(dv), -.win-datepicker .win-datepicker-date.win-order1:lang(fa), -.win-datepicker .win-datepicker-date.win-order1:lang(he), -.win-datepicker .win-datepicker-date.win-order1:lang(ku-Arab), -.win-datepicker .win-datepicker-date.win-order1:lang(pa-Arab), -.win-datepicker .win-datepicker-date.win-order1:lang(prs), -.win-datepicker .win-datepicker-date.win-order1:lang(ps), -.win-datepicker .win-datepicker-date.win-order1:lang(sd-Arab), -.win-datepicker .win-datepicker-date.win-order1:lang(syr), -.win-datepicker .win-datepicker-date.win-order1:lang(ug), -.win-datepicker .win-datepicker-date.win-order1:lang(ur), -.win-datepicker .win-datepicker-date.win-order1:lang(qps-plocm), -.win-datepicker .win-datepicker-year.win-order0:lang(ar), -.win-datepicker .win-datepicker-year.win-order0:lang(dv), -.win-datepicker .win-datepicker-year.win-order0:lang(fa), -.win-datepicker .win-datepicker-year.win-order0:lang(he), -.win-datepicker .win-datepicker-year.win-order0:lang(ku-Arab), -.win-datepicker .win-datepicker-year.win-order0:lang(pa-Arab), -.win-datepicker .win-datepicker-year.win-order0:lang(prs), -.win-datepicker .win-datepicker-year.win-order0:lang(ps), -.win-datepicker .win-datepicker-year.win-order0:lang(sd-Arab), -.win-datepicker .win-datepicker-year.win-order0:lang(syr), -.win-datepicker .win-datepicker-year.win-order0:lang(ug), -.win-datepicker .win-datepicker-year.win-order0:lang(ur), -.win-datepicker .win-datepicker-year.win-order0:lang(qps-plocm) { - margin-right: 0; - margin-left: 20px; -} -.win-timepicker { - display: -ms-inline-flexbox; - display: -webkit-inline-flex; - display: inline-flex; - height: auto; - width: auto; -} -.win-timepicker select { - min-width: 80px; - margin-top: 4px; - margin-bottom: 4px; -} -.win-timepicker .win-timepicker-hour { - margin-right: 20px; -} -.win-timepicker .win-timepicker-period.win-order0 { - margin-right: 20px; -} -.win-timepicker .win-timepicker-minute.win-order1 { - margin-right: 20px; -} -.win-timepicker .win-timepicker-period.win-order0:lang(ar), -.win-timepicker .win-timepicker-period.win-order0:lang(dv), -.win-timepicker .win-timepicker-period.win-order0:lang(fa), -.win-timepicker .win-timepicker-period.win-order0:lang(he), -.win-timepicker .win-timepicker-period.win-order0:lang(ku-Arab), -.win-timepicker .win-timepicker-period.win-order0:lang(pa-Arab), -.win-timepicker .win-timepicker-period.win-order0:lang(prs), -.win-timepicker .win-timepicker-period.win-order0:lang(ps), -.win-timepicker .win-timepicker-period.win-order0:lang(sd-Arab), -.win-timepicker .win-timepicker-period.win-order0:lang(syr), -.win-timepicker .win-timepicker-period.win-order0:lang(ug), -.win-timepicker .win-timepicker-period.win-order0:lang(ur), -.win-timepicker .win-timepicker-period.win-order0:lang(qps-plocm), -.win-timepicker .win-timepicker-hour:lang(ar), -.win-timepicker .win-timepicker-hour:lang(dv), -.win-timepicker .win-timepicker-hour:lang(fa), -.win-timepicker .win-timepicker-hour:lang(he), -.win-timepicker .win-timepicker-hour:lang(ku-Arab), -.win-timepicker .win-timepicker-hour:lang(pa-Arab), -.win-timepicker .win-timepicker-hour:lang(prs), -.win-timepicker .win-timepicker-hour:lang(ps), -.win-timepicker .win-timepicker-hour:lang(sd-Arab), -.win-timepicker .win-timepicker-hour:lang(syr), -.win-timepicker .win-timepicker-hour:lang(ug), -.win-timepicker .win-timepicker-hour:lang(ur), -.win-timepicker .win-timepicker-hour:lang(qps-plocm) { - margin-right: 0; - margin-left: 20px; -} -.win-timepicker .win-timepicker-minute.win-order1:lang(ar), -.win-timepicker .win-timepicker-minute.win-order1:lang(dv), -.win-timepicker .win-timepicker-minute.win-order1:lang(fa), -.win-timepicker .win-timepicker-minute.win-order1:lang(he), -.win-timepicker .win-timepicker-minute.win-order1:lang(ku-Arab), -.win-timepicker .win-timepicker-minute.win-order1:lang(pa-Arab), -.win-timepicker .win-timepicker-minute.win-order1:lang(prs), -.win-timepicker .win-timepicker-minute.win-order1:lang(ps), -.win-timepicker .win-timepicker-minute.win-order1:lang(sd-Arab), -.win-timepicker .win-timepicker-minute.win-order1:lang(syr), -.win-timepicker .win-timepicker-minute.win-order1:lang(ug), -.win-timepicker .win-timepicker-minute.win-order1:lang(ur), -.win-timepicker .win-timepicker-minute.win-order1:lang(qps-plocm), -.win-timepicker .win-timepicker-minute.win-order0:lang(ar), -.win-timepicker .win-timepicker-minute.win-order0:lang(dv), -.win-timepicker .win-timepicker-minute.win-order0:lang(fa), -.win-timepicker .win-timepicker-minute.win-order0:lang(he), -.win-timepicker .win-timepicker-minute.win-order0:lang(ku-Arab), -.win-timepicker .win-timepicker-minute.win-order0:lang(pa-Arab), -.win-timepicker .win-timepicker-minute.win-order0:lang(prs), -.win-timepicker .win-timepicker-minute.win-order0:lang(ps), -.win-timepicker .win-timepicker-minute.win-order0:lang(sd-Arab), -.win-timepicker .win-timepicker-minute.win-order0:lang(syr), -.win-timepicker .win-timepicker-minute.win-order0:lang(ug), -.win-timepicker .win-timepicker-minute.win-order0:lang(ur), -.win-timepicker .win-timepicker-minute.win-order0:lang(qps-plocm) { - margin-left: 20px; - margin-right: 0; -} -body > .win-navigation-backbutton { - position: absolute; - top: 50px; - left: 20px; -} -.win-backbutton, -.win-navigation-backbutton, -.win-back { - touch-action: manipulation; - display: inline-block; - min-width: 0; - min-height: 0; - padding: 0; - text-align: center; - width: 41px; - height: 41px; - font-size: 24px; - line-height: 41px; - vertical-align: baseline; -} -.win-backbutton::before, -.win-back::before { - font-family: "Segoe MDL2 Assets", "Symbols"; - font-weight: normal; - content: "\E0D5"; - vertical-align: 50%; -} -.win-backbutton:lang(ar)::before, -.win-backbutton:lang(dv)::before, -.win-backbutton:lang(fa)::before, -.win-backbutton:lang(he)::before, -.win-backbutton:lang(ku-Arab)::before, -.win-backbutton:lang(pa-Arab)::before, -.win-backbutton:lang(prs)::before, -.win-backbutton:lang(ps)::before, -.win-backbutton:lang(sd-Arab)::before, -.win-backbutton:lang(syr)::before, -.win-backbutton:lang(ug)::before, -.win-backbutton:lang(ur)::before, -.win-backbutton:lang(qps-plocm)::before, -.win-back:lang(ar)::before, -.win-back:lang(dv)::before, -.win-back:lang(fa)::before, -.win-back:lang(he)::before, -.win-back:lang(ku-Arab)::before, -.win-back:lang(pa-Arab)::before, -.win-back:lang(prs)::before, -.win-back:lang(ps)::before, -.win-back:lang(sd-Arab)::before, -.win-back:lang(syr)::before, -.win-back:lang(ug)::before, -.win-back:lang(ur)::before, -.win-back:lang(qps-plocm)::before { - content: "\E0AE"; -} -button.win-navigation-backbutton, -button.win-navigation-backbutton:active, -html.win-hoverable button.win-navigation-backbutton:enabled:hover, -button.win-navigation-backbutton:enabled:hover:active { - background-color: transparent; - border: none; -} -@media (-ms-high-contrast) { - button.win-navigation-backbutton, - button.win-navigation-backbutton:active, - html.win-hoverable button.win-navigation-backbutton:enabled:hover, - button.win-navigation-backbutton:enabled:hover:active { - /* Overwrite default background and border styles from BackButton control's ]]> - /// The BackButton control itself - /// The Back Arrow glyph - /// - /// - BackButton: _Base.Namespace._lazy(function () { - // Statics - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/backbuttonarialabel").value; }, - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get badButtonElement() { return "Invalid argument: For a button, toggle, or flyout command, the element must be null or a button element"; } - }; - - var BackButton = _Base.Class.define(function BackButton_ctor(element, options) { - /// - /// - /// Creates a new BackButton control - /// - /// - /// The DOM element that will host the control. If this parameter is null, this constructor creates one for you. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to - /// one of the control's properties or events. - /// - /// - /// A BackButton control. - /// - /// - /// - - // Check to make sure we weren't duplicated - if (element && element.winControl) { - throw new _ErrorFromName("WinJS.UI.BackButton.DuplicateConstruction", strings.duplicateConstruction); - } - - this._element = element || _Global.document.createElement("button"); - options = options || {}; - - this._initializeButton(); // This will also set the aria-label and tooltip - - this._disposed = false; - - // Remember ourselves - this._element.winControl = this; - - _Control.setOptions(this, options); - - // Add event handlers for this back button instance - this._buttonClickHandler = this._handleBackButtonClick.bind(this); - this._element.addEventListener('click', this._buttonClickHandler, false); - this._navigatedHandler = this._handleNavigatedEvent.bind(this); - Navigation.addEventListener('navigated', this._navigatedHandler, false); - - // Increment reference count / manage add global event handlers - singleton.addRef(); - }, { - - /// - element: { - get: function () { - return this._element; - } - }, - - dispose: function () { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; // Mark this control as disposed. - - // Remove 'navigated' eventhandler for this BackButton - Navigation.removeEventListener('navigated', this._navigatedHandler, false); - - singleton.release(); // Decrement reference count. - - }, - - refresh: function () { - /// - /// - /// Sets the 'disabled' attribute to correct the value based on the current navigation history stack. - /// - /// - /// - if (Navigation.canGoBack) { - this._element.disabled = false; - } else { - this._element.disabled = true; - } - }, - - _initializeButton: function () { - //Final EN-US HTML should be: - // - //Button will automatically be disabled if WinJS.Navigation.history.canGoBack is false. - - // Verify the HTML is a button - if (this._element.tagName !== "BUTTON") { - throw new _ErrorFromName("WinJS.UI.BackButton.BadButtonElement", strings.badButtonElement); - } - - // Attach our css classes - _ElementUtilities.addClass(this._element, navigationBackButtonClass); - - // Attach disposable class. - _ElementUtilities.addClass(this._element, "win-disposable"); - - // Create inner glyph element - this._element.innerHTML = ''; - - // Set the 'disabled' property to the correct value based on the current navigation history stack. - this.refresh(); - - // Set Aria-label and native tooltip to the same localized string equivalent of "Back" - this._element.setAttribute("aria-label", strings.ariaLabel); - this._element.setAttribute("title", strings.ariaLabel); - - // Explicitly set type attribute to avoid the default '; - this._headerTabStopElement = this._headerElement.firstElementChild; - // The purpose of headerWrapperElement is to lay out its children in a flexbox. Ideally, this flexbox would - // be on headerTabStopElement. However, firefox lays out flexboxes with display:flex differently. - // Firefox bug 1014285 (Button with display:inline-flex doesn't layout properly) - // https://bugzilla.mozilla.org/show_bug.cgi?id=1014285 - this._headerWrapperElement = this._headerTabStopElement.firstElementChild; - this._headerContentElement = this._headerWrapperElement.firstElementChild; - this._headerChevronElement = this._headerWrapperElement.lastElementChild; - element.appendChild(this._headerElement); - - this._winKeyboard = new _KeyboardBehavior._WinKeyboard(this._headerElement); - - this._contentElement = _Global.document.createElement("DIV"); - this._contentElement.className = HubSection._ClassName.hubSectionContent; - this._contentElement.style.visibility = "hidden"; - element.appendChild(this._contentElement); - - // Reparent any existing elements inside the new hub section content element. - var elementToMove = this.element.firstChild; - while (elementToMove !== this._headerElement) { - var nextElement = elementToMove.nextSibling; - this._contentElement.appendChild(elementToMove); - elementToMove = nextElement; - } - - this._processors = [ControlProcessor.processAll]; - - _Control.setOptions(this, options); - }, { - /// - element: { - get: function () { - return this._element; - } - }, - /// - /// Gets or sets a value that specifies whether the header is static. Set this value to true to disable clicks and other interactions. - /// - /// - isHeaderStatic: { - get: function () { - return this._isHeaderStatic; - }, - set: function (value) { - this._isHeaderStatic = value; - if (!this._isHeaderStatic) { - this._headerTabStopElement.setAttribute("role", "link"); - _ElementUtilities.addClass(this._headerTabStopElement, HubSection._ClassName.hubSectionInteractive); - } else { - this._headerTabStopElement.setAttribute("role", "heading"); - _ElementUtilities.removeClass(this._headerTabStopElement, HubSection._ClassName.hubSectionInteractive); - } - } - }, - /// - /// Gets the DOM element that hosts the HubSection's content. - /// - /// - contentElement: { - get: function () { - return this._contentElement; - } - }, - /// - /// Get or set the HubSection's header. After you set this property, the Hub renders the header again. - /// - /// - header: { - get: function () { - return this._header; - }, - set: function (value) { - // Render again even if it is equal to itself. - this._header = value; - this._renderHeader(); - } - }, - _setHeaderTemplate: function HubSection_setHeaderTemplate(template) { - this._template = _ElementUtilities._syncRenderer(template); - this._renderHeader(); - }, - _renderHeader: function HubSection_renderHeader() { - if (this._template) { - _Dispose._disposeElement(this._headerContentElement); - _ElementUtilities.empty(this._headerContentElement); - this._template(this, this._headerContentElement); - } - }, - _process: function HubSection_process() { - var that = this; - - this._processed = (this._processors || []).reduce(function (promise, processor) { - return promise.then(function () { - return processor(that.contentElement); - }); - }, this._processed || Promise.as()); - this._processors = null; - - return this._processed; - }, - dispose: function HubSection_dispose() { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - this._processors = null; - - _Dispose._disposeElement(this._headerContentElement); - _Dispose.disposeSubTree(this.contentElement); - } - }, { - // Names of classes used by the HubSection. - _ClassName: { - hubSection: "win-hub-section", - hubSectionHeader: "win-hub-section-header", - hubSectionHeaderTabStop: "win-hub-section-header-tabstop", - hubSectionHeaderWrapper: "win-hub-section-header-wrapper", - hubSectionInteractive: "win-hub-section-header-interactive", - hubSectionHeaderContent: "win-hub-section-header-content", - hubSectionHeaderChevron: "win-hub-section-header-chevron", - hubSectionContent: "win-hub-section-content" - }, - isDeclarativeControlContainer: _BaseUtils.markSupportedForProcessing(function (section, callback) { - if (callback === ControlProcessor.processAll) { - return; - } - - section._processors = section._processors || []; - section._processors.push(callback); - - // Once processed the first time synchronously queue up new processors as they come in - if (section._processed) { - section._process(); - } - }) - }); - - return HubSection; - }) - }); - -}); - - -define('require-style!less/styles-hub',[],function(){}); - -define('require-style!less/colors-hub',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/Hub',[ - '../Core/_Global', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_ErrorFromName', - '../Core/_Events', - '../Core/_Log', - '../Core/_Resources', - '../Core/_WriteProfilerMark', - '../_Accents', - '../Animations', - '../Animations/_TransitionAnimation', - '../BindingList', - '../ControlProcessor', - '../Promise', - '../_Signal', - '../Scheduler', - '../Utilities/_Control', - '../Utilities/_ElementUtilities', - '../Utilities/_Hoverable', - '../Utilities/_UI', - './Hub/_Section', - 'require-style!less/styles-hub', - 'require-style!less/colors-hub' -], function hubInit(_Global, _Base, _BaseUtils, _ErrorFromName, _Events, _Log, _Resources, _WriteProfilerMark, _Accents, Animations, _TransitionAnimation, BindingList, ControlProcessor, Promise, _Signal, Scheduler, _Control, _ElementUtilities, _Hoverable, _UI, _Section) { - "use strict"; - - _Accents.createAccentRule( - ".win-semanticzoom-zoomedoutview .win-hub-section-header-interactive .win-hub-section-header-content,\ - .win-hub-section-header-interactive .win-hub-section-header-chevron", - [{ name: "color", value: _Accents.ColorTypes.accent }]); - - _Base.Namespace.define("WinJS.UI", { - /// - /// - /// Displays sections of content. - /// - /// - /// - /// - /// - /// - ///
HubSection Content
- /// ]]>
- /// Raised when the Hub is about to play an entrance or a transition animation. - /// Raised when a header is invoked. - /// Raised when the loading state changes. - /// The entire Hub control. - /// The progress indicator for the Hub. - /// The viewport of the Hub. - /// The scrollable region of the Hub. - /// - /// - Hub: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - function hubDefaultHeaderTemplate(section) { - var element = _Global.document.createTextNode(typeof section.header === "object" ? JSON.stringify(section.header) : ('' + section.header)); - return element; - } - - var createEvent = _Events._createEventProperty; - var eventNames = { - contentAnimating: "contentanimating", - headerInvoked: "headerinvoked", - loadingStateChanged: "loadingstatechanged" - }; - - // Delay time before progress dots are shown when loading hub section(s) on screen. - var progressDelay = 500; - - var verticalNames = { - scrollPos: "scrollTop", - scrollSize: "scrollHeight", - offsetPos: "offsetTop", - offsetSize: "offsetHeight", - oppositeOffsetSize: "offsetWidth", - marginStart: "marginTop", - marginEnd: "marginBottom", - borderStart: "borderTopWidth", - borderEnd: "borderBottomWidth", - paddingStart: "paddingTop", - paddingEnd: "paddingBottom" - }; - var rtlHorizontalNames = { - scrollPos: "scrollLeft", - scrollSize: "scrollWidth", - offsetPos: "offsetLeft", - offsetSize: "offsetWidth", - oppositeOffsetSize: "offsetHeight", - marginStart: "marginRight", - marginEnd: "marginLeft", - borderStart: "borderRightWidth", - borderEnd: "borderLeftWidth", - paddingStart: "paddingRight", - paddingEnd: "paddingLeft" - }; - var ltrHorizontalNames = { - scrollPos: "scrollLeft", - scrollSize: "scrollWidth", - offsetPos: "offsetLeft", - offsetSize: "offsetWidth", - oppositeOffsetSize: "offsetHeight", - marginStart: "marginLeft", - marginEnd: "marginRight", - borderStart: "borderLeftWidth", - borderEnd: "borderRightWidth", - paddingStart: "paddingLeft", - paddingEnd: "paddingRight" - }; - - var Hub = _Base.Class.define(function Hub_ctor(element, options) { - /// - /// - /// Creates a new Hub control. - /// - /// - /// The DOM element that hosts the Hub control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". For example, to provide a handler for the contentanimating event, - /// add a property named "oncontentanimating" to the options object and set its value to the event handler. - /// - /// - /// The new Hub. - /// - /// - /// - element = element || _Global.document.createElement("DIV"); - options = options || {}; - - if (element.winControl) { - throw new _ErrorFromName("WinJS.UI.Hub.DuplicateConstruction", strings.duplicateConstruction); - } - - this._id = element.id || _ElementUtilities._uniqueID(element); - this._writeProfilerMark("constructor,StartTM"); - - this._windowKeyDownHandlerBound = this._windowKeyDownHandler.bind(this); - _Global.addEventListener('keydown', this._windowKeyDownHandlerBound); - - // Attaching JS control to DOM element - element.winControl = this; - this._element = element; - _ElementUtilities.addClass(this.element, Hub._ClassName.hub); - _ElementUtilities.addClass(this.element, "win-disposable"); - - this._viewportElement = _Global.document.createElement("DIV"); - this._viewportElement.className = Hub._ClassName.hubViewport; - this._element.appendChild(this._viewportElement); - this._viewportElement.setAttribute("role", "group"); - this._viewportElement.setAttribute("aria-label", strings.hubViewportAriaLabel); - - this._surfaceElement = _Global.document.createElement("DIV"); - this._surfaceElement.className = Hub._ClassName.hubSurface; - this._viewportElement.appendChild(this._surfaceElement); - - // Start invisible so that you do not see the content loading until the sections are ready. - this._visible = false; - this._viewportElement.style.opacity = 0; - - if (!options.orientation) { - this._orientation = _UI.Orientation.horizontal; - _ElementUtilities.addClass(this.element, Hub._ClassName.hubHorizontal); - } - - this._fireEntrance = true; - this._animateEntrance = true; - this._loadId = 0; - this.runningAnimations = new Promise.wrap(); - this._currentIndexForSezo = 0; - - // This internally assigns this.sections which causes section to be used (even from options) before - // scrollPosition or sectionOnScreen. - this._parse(); - - _Control.setOptions(this, options); - - _ElementUtilities._addEventListener(this.element, "focusin", this._focusin.bind(this), false); - this.element.addEventListener("keydown", this._keyDownHandler.bind(this)); - this.element.addEventListener("click", this._clickHandler.bind(this)); - this._resizeHandlerBound = this._resizeHandler.bind(this); - this.element.addEventListener("mselementresize", this._resizeHandlerBound); - _ElementUtilities._resizeNotifier.subscribe(this.element, this._resizeHandlerBound); - this._viewportElement.addEventListener("scroll", this._scrollHandler.bind(this)); - this._surfaceElement.addEventListener("mselementresize", this._contentResizeHandler.bind(this)); - - this._handleSectionChangedBind = this._handleSectionChanged.bind(this); - this._handleSectionInsertedBind = this._handleSectionInserted.bind(this); - this._handleSectionMovedBind = this._handleSectionMoved.bind(this); - this._handleSectionRemovedBind = this._handleSectionRemoved.bind(this); - this._handleSectionReloadBind = this._handleSectionReload.bind(this); - - this._refresh(); - - this._writeProfilerMark("constructor,StopTM"); - }, { - /// - element: { - get: function () { - return this._element; - } - }, - /// - /// Gets or sets the orientation of sections within the Hub. - /// - /// - orientation: { - get: function () { - return this._orientation; - }, - set: function (value) { - if (value === this._orientation) { - return; - } - this._measured = false; - // clear existing scroll before we switch orientation - if (this._names) { // handle setting orientation before we measure - var newScrollPos = {}; - newScrollPos[this._names.scrollPos] = 0; - _ElementUtilities.setScrollPosition(this._viewportElement, newScrollPos); - } - if (value === _UI.Orientation.vertical) { - _ElementUtilities.removeClass(this.element, Hub._ClassName.hubHorizontal); - _ElementUtilities.addClass(this.element, Hub._ClassName.hubVertical); - } else { - value = _UI.Orientation.horizontal; - _ElementUtilities.removeClass(this.element, Hub._ClassName.hubVertical); - _ElementUtilities.addClass(this.element, Hub._ClassName.hubHorizontal); - } - this._orientation = value; - Scheduler.schedule(this._updateSnapList.bind(this), Scheduler.Priority.idle); - } - }, - /// - /// Gets or sets the WinJS.Binding.List of HubSection objects that belong to this Hub. - /// - /// - sections: { - get: function () { - if (this._pendingSections) { - return this._pendingSections; - } - return this._sections; - }, - set: function (value) { - var resetScrollPosition = !this._pendingSections; - this._pendingSections = value; - this._refresh(); - if (resetScrollPosition) { - this.scrollPosition = 0; - } - } - }, - /// - /// Gets or sets the WinJS.Binding.Template or template function that creates the DOM elements - /// which represent the header for each HubSection. Each header can - /// contain multiple DOM elements, but we recommend that it have a single - /// root element. - /// - /// - headerTemplate: { - get: function () { - if (this._pendingHeaderTemplate) { - return this._pendingHeaderTemplate; - } - - if (!this._headerTemplate) { - this._headerTemplate = hubDefaultHeaderTemplate; - } - - return this._headerTemplate; - }, - set: function (value) { - this._pendingHeaderTemplate = value || hubDefaultHeaderTemplate; - this._refresh(); - } - }, - /// - /// Gets or sets the position of the Hub's scrollbar. - /// - /// - scrollPosition: { - get: function () { - if (+this._pendingScrollLocation === this._pendingScrollLocation) { - return this._pendingScrollLocation; - } - - this._measure(); - return this._scrollPosition; - }, - set: function (value) { - value = Math.max(0, value); - if (this._pendingRefresh) { - // Unable to constrain length because sections may have changed. - this._pendingScrollLocation = value; - this._pendingSectionOnScreen = null; - } else { - this._measure(); - var targetScrollPos = Math.max(0, Math.min(this._scrollLength - this._viewportSize, value)); - this._scrollPosition = targetScrollPos; - var newScrollPos = {}; - newScrollPos[this._names.scrollPos] = targetScrollPos; - _ElementUtilities.setScrollPosition(this._viewportElement, newScrollPos); - } - } - }, - - /// - /// Gets or sets the index of first section in view. This property is useful for restoring a previous view when your app launches or resumes. - /// - /// - sectionOnScreen: { - get: function () { - if (+this._pendingSectionOnScreen === this._pendingSectionOnScreen) { - return this._pendingSectionOnScreen; - } - - this._measure(); - for (var i = 0; i < this._sectionSizes.length; i++) { - var sectionSize = this._sectionSizes[i]; - if ((sectionSize.offset + sectionSize.size - sectionSize.borderEnd - sectionSize.paddingEnd) > (this._scrollPosition + this._startSpacer + sectionSize.borderStart + sectionSize.paddingStart)) { - return i; - } - } - return -1; - }, - set: function (value) { - value = Math.max(0, value); - if (this._pendingRefresh) { - this._pendingSectionOnScreen = value; - this._pendingScrollLocation = null; - } else { - this._measure(); - if (value >= 0 && value < this._sectionSizes.length) { - this._scrollToSection(value); - } - } - } - }, - /// - /// Gets or sets the index of first section at least partially in view. Use for animations. - /// - /// - indexOfFirstVisible: { - get: function () { - this._measure(); - for (var i = 0; i < this._sectionSizes.length; i++) { - var sectionSize = this._sectionSizes[i]; - if ((sectionSize.offset + sectionSize.size - sectionSize.borderEnd - sectionSize.paddingEnd) > this._scrollPosition) { - return i; - } - } - return -1; - } - }, - /// - /// Gets or sets the index of last section at least partially in view. Use for animations. - /// - /// - indexOfLastVisible: { - get: function () { - this._measure(); - for (var i = this._sectionSizes.length - 1; i >= 0; i--) { - var sectionSize = this._sectionSizes[i]; - if ((sectionSize.offset + sectionSize.paddingStart + sectionSize.borderStart) < (this._scrollPosition + this._viewportSize)) { - return i; - } - } - return -1; - } - }, - - /// - /// Raised when the user clicks on an interactive header. - /// - /// - onheaderinvoked: createEvent(eventNames.headerInvoked), - - /// - /// Raised when the loadingState of the Hub changes. - /// - /// - onloadingstatechanged: createEvent(eventNames.loadingStateChanged), - - /// - /// Raised when Hub is about to play entrance, contentTransition, insert, or remove animations. - /// - /// - oncontentanimating: createEvent(eventNames.contentAnimating), - - _refresh: function hub_refresh() { - if (this._pendingRefresh) { - return; - } - - this._loadId++; - this._setState(Hub.LoadingState.loading); - // This is to coalesce property setting operations such as sections and scrollPosition. - this._pendingRefresh = true; - - Scheduler.schedule(this._refreshImpl.bind(this), Scheduler.Priority.high); - }, - _refreshImpl: function hub_refreshImpl() { - if (this._disposed) { - return; - } - - var fadeOutAnimation = Promise.wrap(); - if (this._pendingSections) { - this._animateEntrance = true; - this._fireEntrance = !this._visible; - if (!this._fireEntrance) { - this._visible = false; - this._viewportElement.style.opacity = 0; - - if (_TransitionAnimation.isAnimationEnabled()) { - var animateTransition = this._fireEvent(Hub._EventName.contentAnimating, { - type: Hub.AnimationType.contentTransition - }); - - if (animateTransition) { - this._viewportElement.style["-ms-overflow-style"] = "none"; - fadeOutAnimation = Animations.fadeOut(this._viewportElement).then(function () { - this._viewportElement.style["-ms-overflow-style"] = ""; - }.bind(this)); - } - this._animateEntrance = animateTransition; - } - } - } - - fadeOutAnimation.done(this._applyProperties.bind(this)); - }, - _applyProperties: function hub_applyProperties() { - if (this._disposed) { - return; - } - - this._pendingRefresh = false; - - var needsToLoadSections = false; - if (this._pendingSections) { - needsToLoadSections = true; - this._updateEvents(this._sections, this._pendingSections); - this._sections = this._pendingSections; - this._pendingSections = null; - // Remove any declaratively specified hub sections before attachSections. - while (this.element.firstElementChild !== this._viewportElement) { - var toRemove = this.element.firstElementChild; - toRemove.parentNode.removeChild(toRemove); - } - _ElementUtilities.empty(this._surfaceElement); - } - - if (this._pendingHeaderTemplate) { - this._headerTemplate = this._pendingHeaderTemplate; - this._pendingHeaderTemplate = null; - } - - this._assignHeaderTemplate(); - - if (needsToLoadSections) { - this._attachSections(); - } - - // Scroll after headers are rendered and sections are attached so the scroll thumb is correct. - if (+this._pendingSectionOnScreen === this._pendingSectionOnScreen) { - // If there are both pending section on screen and scroll location use section on screen. - this.sectionOnScreen = this._pendingSectionOnScreen; - } else if (+this._pendingScrollLocation === this._pendingScrollLocation) { - this.scrollPosition = this._pendingScrollLocation; - } else { - // Sections reset without sectionOnScreen or scrollPosition APIs. - this.scrollPosition = 0; - } - - this._pendingSectionOnScreen = null; - this._pendingScrollLocation = null; - - // Using current (or new) scroll location load the sections - this._setState(Hub.LoadingState.loading); - this._loadSections(); - }, - _handleSectionChanged: function hub_handleSectionChanged(ev) { - // Change is triggered by binding list setAt() API. - if (this._pendingSections) { - return; - } - - var newSection = ev.detail.newValue; - var oldSection = ev.detail.oldValue; - newSection._setHeaderTemplate(this.headerTemplate); - if (newSection.element !== oldSection.element) { - if (newSection.element.parentNode === this._surfaceElement) { - throw new _ErrorFromName("WinJS.UI.Hub.DuplicateSection", strings.duplicateSection); - } - - this._surfaceElement.insertBefore(newSection.element, oldSection.element); - this._surfaceElement.removeChild(oldSection.element); - this._measured = false; - - this._setState(Hub.LoadingState.loading); - this._loadSections(); - } - }, - _handleSectionInserted: function hub_handleSectionInserted(ev) { - // Insert is triggered by binding list insert APIs such as splice(), push(), and unshift(). - if (this._pendingSections) { - return; - } - - var index = ev.detail.index; - var section = ev.detail.value; - - if (section._animation) { - section._animation.cancel(); - } - - var animation; - var result = this._fireEvent(Hub._EventName.contentAnimating, { - type: Hub.AnimationType.insert, - index: index, - section: section - }); - - if (result) { - - var affectedElements = []; - - for (var i = index + 1; i < this.sections.length; i++) { - affectedElements.push(this.sections.getAt(i).element); - } - - animation = new Animations._createUpdateListAnimation([section.element], [], affectedElements); - } - - if (section.element.parentNode === this._surfaceElement) { - throw new _ErrorFromName("WinJS.UI.Hub.DuplicateSection", strings.duplicateSection); - } - - section._setHeaderTemplate(this.headerTemplate); - if (index < this.sections.length - 1) { - this._surfaceElement.insertBefore(section.element, this.sections.getAt(index + 1).element); - } else { - this._surfaceElement.appendChild(section.element); - } - this._measured = false; - - if (animation) { - var insertAnimation = animation.execute(); - this.runningAnimations = Promise.join([this.runningAnimations, insertAnimation]); - } - - this._setState(Hub.LoadingState.loading); - this._loadSections(); - }, - _handleSectionMoved: function hub_handleSectionMoved(ev) { - // Move is triggered by binding list move() API. - if (this._pendingSections) { - return; - } - - var newIndex = ev.detail.newIndex; - var section = ev.detail.value; - - if (newIndex < this.sections.length - 1) { - this._surfaceElement.insertBefore(section.element, this.sections.getAt(newIndex + 1).element); - } else { - this._surfaceElement.appendChild(section.element); - } - this._measured = false; - - this._setState(Hub.LoadingState.loading); - this._loadSections(); - }, - _handleSectionRemoved: function hub_handleSectionRemoved(ev) { - // Removed is triggered by binding list removal APIs such as splice(), pop(), and shift(). - if (this._pendingSections) { - return; - } - - var section = ev.detail.value; - var index = ev.detail.index; - - var animationPromise = Promise.wrap(); - var result = this._fireEvent(Hub._EventName.contentAnimating, { - type: Hub.AnimationType.remove, - index: index, - section: section - }); - - if (result) { - var affectedElements = []; - - for (var i = index; i < this.sections.length; i++) { - affectedElements.push(this.sections.getAt(i).element); - } - - var animation = new Animations._createUpdateListAnimation([], [section.element], affectedElements); - - this._measure(); - var offsetTop = section.element.offsetTop; - var offsetLeft = section.element.offsetLeft; - section.element.style.position = "absolute"; - section.element.style.top = offsetTop; - section.element.style.left = offsetLeft; - section.element.style.opacity = 0; - this._measured = false; - - animationPromise = animation.execute().then(function () { - section.element.style.position = ""; - section.element.style.top = ""; - section.element.style.left = ""; - section.element.style.opacity = 1; - }.bind(this)); - } - - animationPromise.done(function () { - if (!this._disposed) { - this._surfaceElement.removeChild(section.element); - this._measured = false; - } - }.bind(this)); - - // Store animation promise in case it is inserted before remove animation finishes. - section._animation = animationPromise; - this.runningAnimations = Promise.join([this.runningAnimations, animationPromise]); - - this._setState(Hub.LoadingState.loading); - this._loadSections(); - }, - _handleSectionReload: function hub_handleSectionReload() { - // Reload is triggered by large operations on the binding list such as reverse(). This causes - // _pendingSections to be true which ignores future insert/remove/modified/moved events until the new - // sections list is applied. - this.sections = this.sections; - }, - _updateEvents: function hub_updateEvents(oldSections, newSections) { - if (oldSections) { - oldSections.removeEventListener("itemchanged", this._handleSectionChangedBind); - oldSections.removeEventListener("iteminserted", this._handleSectionInsertedBind); - oldSections.removeEventListener("itemmoved", this._handleSectionMovedBind); - oldSections.removeEventListener("itemremoved", this._handleSectionRemovedBind); - oldSections.removeEventListener("reload", this._handleSectionReloadBind); - } - - if (newSections) { - newSections.addEventListener("itemchanged", this._handleSectionChangedBind); - newSections.addEventListener("iteminserted", this._handleSectionInsertedBind); - newSections.addEventListener("itemmoved", this._handleSectionMovedBind); - newSections.addEventListener("itemremoved", this._handleSectionRemovedBind); - newSections.addEventListener("reload", this._handleSectionReloadBind); - } - }, - _attachSections: function hub_attachSections() { - this._measured = false; - for (var i = 0; i < this.sections.length; i++) { - var section = this._sections.getAt(i); - if (section._animation) { - section._animation.cancel(); - } - if (section.element.parentNode === this._surfaceElement) { - throw new _ErrorFromName("WinJS.UI.Hub.DuplicateSection", strings.duplicateSection); - } - this._surfaceElement.appendChild(section.element); - } - }, - _assignHeaderTemplate: function hub_assignHeaderTemplate() { - this._measured = false; - for (var i = 0; i < this.sections.length; i++) { - var section = this._sections.getAt(i); - section._setHeaderTemplate(this.headerTemplate); - } - }, - _loadSection: function hub_loadSection(index) { - var section = this._sections.getAt(index); - return section._process().then(function resetVisibility() { - var style = section.contentElement.style; - if (style.visibility !== "") { - style.visibility = ""; - } - }); - }, - _loadSections: function hub_loadSections() { - // Used to know if another load has interrupted this one. - this._loadId++; - var loadId = this._loadId; - var that = this; - var onScreenItemsAnimatedPromise = Promise.wrap(); - var sectionIndicesToLoad = []; - var allSectionsLoadedPromise = Promise.wrap(); - - function loadNextSectionAfterPromise(promise) { - promise.then(function () { - Scheduler.schedule(loadNextSection, Scheduler.Priority.idle); - }); - } - - function loadNextSection() { - if (loadId === that._loadId && !that._disposed) { - if (sectionIndicesToLoad.length) { - var index = sectionIndicesToLoad.shift(); - var loadedPromise = that._loadSection(index); - loadNextSectionAfterPromise(loadedPromise); - } else { - allSectionsLoadedSignal.complete(); - } - } - } - - if (!this._showProgressPromise) { - this._showProgressPromise = Promise.timeout(progressDelay).then(function () { - if (this._disposed) { - return; - } - - if (!this._progressBar) { - this._progressBar = _Global.document.createElement("progress"); - _ElementUtilities.addClass(this._progressBar, Hub._ClassName.hubProgress); - this._progressBar.max = 100; - } - if (!this._progressBar.parentNode) { - this.element.insertBefore(this._progressBar, this._viewportElement); - } - this._showProgressPromise = null; - }.bind(this), function () { - this._showProgressPromise = null; - }.bind(this)); - } - - if (this.sections.length) { - var allSectionsLoadedSignal = new _Signal(); - allSectionsLoadedPromise = allSectionsLoadedSignal.promise; - // Synchronously load the sections on screen. - var synchronousProcessPromises = []; - var start = Math.max(0, this.indexOfFirstVisible); - var end = Math.max(0, this.indexOfLastVisible); - for (var i = start; i <= end; i++) { - synchronousProcessPromises.push(this._loadSection(i)); - } - - // Determine the order to load the rest of the sections. - start--; - end++; - while (start >= 0 || end < this.sections.length) { - if (end < this.sections.length) { - sectionIndicesToLoad.push(end); - end++; - } - if (start >= 0) { - sectionIndicesToLoad.push(start); - start--; - } - } - - var onScreenSectionsLoadedPromise = Promise.join(synchronousProcessPromises); - - // In case there are overlapping load calls - onScreenSectionsLoadedPromise.done(function () { - if (loadId === this._loadId && !that._disposed) { - if (this._showProgressPromise) { - this._showProgressPromise.cancel(); - } - - if (this._progressBar && this._progressBar.parentNode) { - this._progressBar.parentNode.removeChild(this._progressBar); - } - - Scheduler.schedule(function Hub_entranceAnimation() { - if (loadId === this._loadId && !that._disposed) { - if (!this._visible) { - this._visible = true; - this._viewportElement.style.opacity = 1; - - if (this._animateEntrance && _TransitionAnimation.isAnimationEnabled()) { - var eventDetail = { - type: Hub.AnimationType.entrance - }; - - if (!this._fireEntrance || this._fireEvent(Hub._EventName.contentAnimating, eventDetail)) { - this._viewportElement.style["-ms-overflow-style"] = "none"; - onScreenItemsAnimatedPromise = Animations.enterContent(this._viewportElement).then(function () { - this._viewportElement.style["-ms-overflow-style"] = ""; - }.bind(this)); - } - } - if (this._element === _Global.document.activeElement) { - this._moveFocusIn(this.sectionOnScreen); - } - } - } - }, Scheduler.Priority.high, this, "WinJS.UI.Hub.entranceAnimation"); - } - }.bind(this)); - - loadNextSectionAfterPromise(onScreenSectionsLoadedPromise); - } else { - if (this._showProgressPromise) { - this._showProgressPromise.cancel(); - } - - if (this._progressBar && this._progressBar.parentNode) { - this._progressBar.parentNode.removeChild(this._progressBar); - } - } - - Promise.join([this.runningAnimations, onScreenItemsAnimatedPromise, allSectionsLoadedPromise]).done(function () { - if (loadId === this._loadId && !that._disposed) { - this.runningAnimations = Promise.wrap(); - if (this._measured && this._scrollLength !== this._viewportElement[this._names.scrollSize]) { - // A section changed size during processing. Invalidate the Hub's measurements so that its - // API's work correctly within the loadingState=complete handler. - this._measured = false; - } - this._setState(Hub.LoadingState.complete); - Scheduler.schedule(this._updateSnapList.bind(this), Scheduler.Priority.idle); - } - }.bind(this)); - }, - /// - loadingState: { - get: function () { - return this._loadingState; - } - }, - _setState: function Hub_setState(state) { - if (state !== this._loadingState) { - this._writeProfilerMark("loadingStateChanged:" + state + ",info"); - this._loadingState = state; - var eventObject = _Global.document.createEvent("CustomEvent"); - eventObject.initCustomEvent(Hub._EventName.loadingStateChanged, true, false, { loadingState: state }); - this._element.dispatchEvent(eventObject); - } - }, - _parse: function hub_parse() { - var hubSections = []; - var hubSectionEl = this.element.firstElementChild; - - while (hubSectionEl !== this._viewportElement) { - ControlProcessor.processAll(hubSectionEl); - - var hubSectionContent = hubSectionEl.winControl; - if (hubSectionContent) { - hubSections.push(hubSectionContent); - } else { - throw new _ErrorFromName("WinJS.UI.Hub.InvalidContent", strings.invalidContent); - } - - var nextSectionEl = hubSectionEl.nextElementSibling; - hubSectionEl = nextSectionEl; - } - - this.sections = new BindingList.List(hubSections); - }, - _fireEvent: function hub_fireEvent(type, detail) { - // Returns true if ev.preventDefault() was not called - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(type, true, true, detail); - return this.element.dispatchEvent(event); - }, - - _findHeaderTabStop: function hub_findHeaderTabStop(element) { - if (element.parentNode) { - if (_ElementUtilities._matchesSelector(element, ".win-hub-section-header-tabstop, .win-hub-section-header-tabstop *")) { - while (!_ElementUtilities.hasClass(element, "win-hub-section-header-tabstop")) { - element = element.parentElement; - } - return element; - } - } - return null; - }, - _isInteractive: function hub_isInteractive(element) { - // Helper method to skip keyboarding and clicks - - while (element && element !== _Global.document.body) { - if (element.classList.contains("win-interactive")) { - return true; - } - element = element.parentElement; - } - return false; - }, - _clickHandler: function hub_clickHandler(ev) { - var headerTabStopElement = this._findHeaderTabStop(ev.target); - if (headerTabStopElement && !this._isInteractive(ev.target)) { - var section = headerTabStopElement.parentElement.parentElement.winControl; - if (!section.isHeaderStatic) { - var sectionIndex = this.sections.indexOf(section); - this._fireEvent(Hub._EventName.headerInvoked, { - index: sectionIndex, - section: section - }); - } - } - }, - _resizeHandler: function hub_resizeHandler() { - // Viewport needs to be measured - this._measured = false; - Scheduler.schedule(this._updateSnapList.bind(this), Scheduler.Priority.idle); - }, - _contentResizeHandler: function hub_contentResizeHandler() { - // Sections and scroll length need to be measured - this._measured = false; - Scheduler.schedule(this._updateSnapList.bind(this), Scheduler.Priority.idle); - }, - _scrollHandler: function hub_scrollHandler() { - // Scroll location needs to be retrieved - this._measured = false; - - if (this._pendingSections) { - return; - } - - // Scroll events caused by users overwrite pending API modifications to scrollposition. - this._pendingScrollLocation = null; - this._pendingSectionOnScreen = null; - - if (!this._pendingScrollHandler) { - this._pendingScrollHandler = _BaseUtils._requestAnimationFrame(function () { - this._pendingScrollHandler = null; - - if (this._pendingSections) { - return; - } - - if (this.loadingState !== Hub.LoadingState.complete) { - this._loadSections(); - } - }.bind(this)); - } - }, - _measure: function hub_measure() { - // Any time a size changes (section growing, window resizing, etc) cachedSizes should be set to false - // and any time the variables need to be read again we should measure the variables. To avoid a lot of - // seperate layouts we measure the variables in a single batch. - if (!this._measured || this._scrollLength === 0) { - this._writeProfilerMark("measure,StartTM"); - this._measured = true; - - this._rtl = _Global.getComputedStyle(this._element, null).direction === "rtl"; - - if (this.orientation === _UI.Orientation.vertical) { - this._names = verticalNames; - } else { - if (this._rtl) { - this._names = rtlHorizontalNames; - } else { - this._names = ltrHorizontalNames; - } - } - - this._viewportSize = this._viewportElement[this._names.offsetSize]; - this._viewportOppositeSize = this._viewportElement[this._names.oppositeOffsetSize]; - this._scrollPosition = _ElementUtilities.getScrollPosition(this._viewportElement)[this._names.scrollPos]; - this._scrollLength = this._viewportElement[this._names.scrollSize]; - - var surfaceElementComputedStyle = _Global.getComputedStyle(this._surfaceElement); - this._startSpacer = parseFloat(surfaceElementComputedStyle[this._names.marginStart]) + parseFloat(surfaceElementComputedStyle[this._names.borderStart]) + parseFloat(surfaceElementComputedStyle[this._names.paddingStart]); - this._endSpacer = parseFloat(surfaceElementComputedStyle[this._names.marginEnd]) + parseFloat(surfaceElementComputedStyle[this._names.borderEnd]) + parseFloat(surfaceElementComputedStyle[this._names.paddingEnd]); - - this._sectionSizes = []; - for (var i = 0; i < this.sections.length; i++) { - var section = this.sections.getAt(i); - var computedSectionStyle = _Global.getComputedStyle(section.element); - this._sectionSizes[i] = { - offset: section.element[this._names.offsetPos], - // Reminder: offsetWidth doesn't include margins and also rounds. - size: section.element[this._names.offsetSize], - marginStart: parseFloat(computedSectionStyle[this._names.marginStart]), - marginEnd: parseFloat(computedSectionStyle[this._names.marginEnd]), - borderStart: parseFloat(computedSectionStyle[this._names.borderStart]), - borderEnd: parseFloat(computedSectionStyle[this._names.borderEnd]), - paddingStart: parseFloat(computedSectionStyle[this._names.paddingStart]), - paddingEnd: parseFloat(computedSectionStyle[this._names.paddingEnd]) - }; - - if (this._rtl && this.orientation === _UI.Orientation.horizontal) { - this._sectionSizes[i].offset = this._viewportSize - (this._sectionSizes[i].offset + this._sectionSizes[i].size); - } - } - - this._writeProfilerMark("measure,StopTM"); - } - }, - _updateSnapList: function hub_updateSnapList() { - this._writeProfilerMark("updateSnapList,StartTM"); - this._measure(); - - var snapList = "snapList("; - for (var i = 0; i < this._sectionSizes.length; i++) { - if (i > 0) { - snapList += ","; - } - var sectionSize = this._sectionSizes[i]; - snapList += (sectionSize.offset - sectionSize.marginStart - this._startSpacer) + "px"; - } - snapList += ")"; - - var snapListY = ""; - var snapListX = ""; - if (this.orientation === _UI.Orientation.vertical) { - snapListY = snapList; - } else { - snapListX = snapList; - } - - if (this._lastSnapPointY !== snapListY) { - this._lastSnapPointY = snapListY; - this._viewportElement.style['-ms-scroll-snap-points-y'] = snapListY; - } - - if (this._lastSnapPointX !== snapListX) { - this._lastSnapPointX = snapListX; - this._viewportElement.style['-ms-scroll-snap-points-x'] = snapListX; - } - - this._writeProfilerMark("updateSnapList,StopTM"); - }, - _scrollToSection: function Hub_scrollToSection(index, withAnimation) { - this._measure(); - var sectionSize = this._sectionSizes[index]; - var scrollPositionToShowStartMargin = Math.min(this._scrollLength - this._viewportSize, sectionSize.offset - sectionSize.marginStart - this._startSpacer); - - this._scrollTo(scrollPositionToShowStartMargin, withAnimation); - }, - _ensureVisible: function hub_ensureVisible(index, withAnimation) { - this._measure(); - var targetScrollPos = this._ensureVisibleMath(index, this._scrollPosition); - this._scrollTo(targetScrollPos, withAnimation); - }, - _ensureVisibleMath: function hub_ensureVisibleMath(index, targetScrollPos) { - this._measure(); - var sectionSize = this._sectionSizes[index]; - - var scrollPositionToShowStartMargin = Math.min(this._scrollLength - this._viewportSize, sectionSize.offset - sectionSize.marginStart - this._startSpacer); - var scrollPositionToShowEndMargin = Math.max(0, sectionSize.offset + sectionSize.size + sectionSize.marginEnd + this._endSpacer - this._viewportSize + 1); - if (targetScrollPos > scrollPositionToShowStartMargin) { - targetScrollPos = scrollPositionToShowStartMargin; - } else if (targetScrollPos < scrollPositionToShowEndMargin) { - targetScrollPos = Math.min(scrollPositionToShowStartMargin, scrollPositionToShowEndMargin); - } - - return targetScrollPos; - }, - _scrollTo: function hub_scrollTo(scrollPos, withAnimation) { - this._scrollPosition = scrollPos; - if (withAnimation) { - if (this.orientation === _UI.Orientation.vertical) { - _ElementUtilities._zoomTo(this._viewportElement, { contentX: 0, contentY: this._scrollPosition, viewportX: 0, viewportY: 0 }); - } else { - _ElementUtilities._zoomTo(this._viewportElement, { contentX: this._scrollPosition, contentY: 0, viewportX: 0, viewportY: 0 }); - } - } else { - var newScrollPos = {}; - newScrollPos[this._names.scrollPos] = this._scrollPosition; - _ElementUtilities.setScrollPosition(this._viewportElement, newScrollPos); - } - }, - _windowKeyDownHandler: function hub_windowKeyDownHandler(ev) { - // Include tab and shift tab. Note: Alt Key + Tab and Windows Key + Tab do not fire keydown with ev.key === "Tab". - if (ev.keyCode === Key.tab) { - this._tabSeenLast = true; - - var that = this; - _BaseUtils._yieldForEvents(function () { - that._tabSeenLast = false; - }); - } - }, - _focusin: function hub_focusin(ev) { - // On focus we call ensureVisible to handle the tab or shift/tab to header. However if the - // focus was caused by a pointer down event we skip the focus. - if (this._tabSeenLast) { - var headerTabStopElement = this._findHeaderTabStop(ev.target); - if (headerTabStopElement && !this._isInteractive(ev.target)) { - var sectionIndex = this.sections.indexOf(headerTabStopElement.parentElement.parentElement.winControl); - if (sectionIndex > -1) { - this._ensureVisible(sectionIndex, true); - } - } - } - - // Always remember the focused section for SemanticZoom. - var sectionElement = ev.target; - while (sectionElement && !_ElementUtilities.hasClass(sectionElement, _Section.HubSection._ClassName.hubSection)) { - sectionElement = sectionElement.parentElement; - } - if (sectionElement) { - var sectionIndex = this.sections.indexOf(sectionElement.winControl); - if (sectionIndex > -1) { - this._currentIndexForSezo = sectionIndex; - } - } - - if (ev.target === this.element) { - var indexToFocus; - if (+this._sectionToFocus === this._sectionToFocus && this._sectionToFocus >= 0 && this._sectionToFocus < this.sections.length) { - indexToFocus = this._sectionToFocus; - this._sectionToFocus = null; - } else { - indexToFocus = this.sectionOnScreen; - } - - this._moveFocusIn(indexToFocus); - } - }, - _moveFocusIn: function hub_moveFocusIn(indexToFocus) { - if (indexToFocus >= 0) { - for (var i = indexToFocus; i < this.sections.length; i++) { - var section = this.sections.getAt(i); - - var focusAttempt = _ElementUtilities._trySetActive(section._headerTabStopElement, this._viewportElement); - - if (focusAttempt) { - return; - } - - if (_ElementUtilities._setActiveFirstFocusableElement(section.contentElement, this._viewportElement)) { - return; - } - } - - for (var i = indexToFocus - 1; i >= 0; i--) { - var section = this.sections.getAt(i); - - if (_ElementUtilities._setActiveFirstFocusableElement(section.contentElement, this._viewportElement)) { - return; - } - - var focusAttempt = _ElementUtilities._trySetActive(section._headerTabStopElement, this._viewportElement); - - if (focusAttempt) { - return; - } - } - } - }, - _keyDownHandler: function hub_keyDownHandler(ev) { - if (this._isInteractive(ev.target) || _ElementUtilities._hasCursorKeysBehaviors(ev.target)) { - return; - } - - var leftKey = this._rtl ? Key.rightArrow : Key.leftArrow; - var rightKey = this._rtl ? Key.leftArrow : Key.rightArrow; - - if (ev.keyCode === Key.upArrow || ev.keyCode === Key.downArrow || ev.keyCode === Key.leftArrow || ev.keyCode === Key.rightArrow || ev.keyCode === Key.pageUp || ev.keyCode === Key.pageDown) { - var headerTabStopElement = this._findHeaderTabStop(ev.target); - if (headerTabStopElement) { - var currentSection = this.sections.indexOf(headerTabStopElement.parentElement.parentElement.winControl); - var targetSectionIndex; - var useEnsureVisible = false; - // Page up/down go to the next/previous header and line it up with the app header. Up/Right/Down/Left - // move focus to the next/previous header and move it on screen (app header distance from either edge). - if (ev.keyCode === Key.pageDown || - (this.orientation === _UI.Orientation.horizontal && ev.keyCode === rightKey) || - (this.orientation === _UI.Orientation.vertical && ev.keyCode === Key.downArrow)) { - // Do not include hidden headers. - for (var i = currentSection + 1; i < this.sections.length; i++) { - if (this._tryFocus(i)) { - targetSectionIndex = i; - break; - } - } - } else if (ev.keyCode === Key.pageUp || - (this.orientation === _UI.Orientation.horizontal && ev.keyCode === leftKey) || - (this.orientation === _UI.Orientation.vertical && ev.keyCode === Key.upArrow)) { - // Do not include hidden headers. - for (var i = currentSection - 1; i >= 0; i--) { - if (this._tryFocus(i)) { - targetSectionIndex = i; - break; - } - } - } - if (ev.keyCode === Key.upArrow || ev.keyCode === Key.downArrow || ev.keyCode === Key.leftArrow || ev.keyCode === Key.rightArrow) { - useEnsureVisible = true; - } - - if (+targetSectionIndex === targetSectionIndex) { - if (useEnsureVisible) { - this._ensureVisible(targetSectionIndex, true); - } else { - this._scrollToSection(targetSectionIndex, true); - } - ev.preventDefault(); - } - } - } else if (ev.keyCode === Key.home || ev.keyCode === Key.end) { - // Home/End scroll to start/end and leave focus where it is. - this._measure(); - var maxScrollPos = Math.max(0, this._scrollLength - this._viewportSize); - this._scrollTo(ev.keyCode === Key.home ? 0 : maxScrollPos, true); - ev.preventDefault(); - } - }, - _tryFocus: function hub_tryFocus(index) { - var targetSection = this.sections.getAt(index); - - _ElementUtilities._setActive(targetSection._headerTabStopElement, this._viewportElement); - - return _Global.document.activeElement === targetSection._headerTabStopElement; - }, - /// - /// Gets a ZoomableView. This API supports the SemanticZoom infrastructure - /// and is not intended to be used directly from your code. - /// - /// - zoomableView: { - get: function zoomableView_get() { - if (!this._zoomableView) { - this._zoomableView = new ZoomableView(this); - } - - return this._zoomableView; - } - }, - _getPanAxis: function hub_getPanAxis() { - return this.orientation === _UI.Orientation.horizontal ? "horizontal" : "vertical"; - }, - _configureForZoom: function hub_configureForZoom() { - // Nothing to configure. - }, - _setCurrentItem: function hub_setCurrentItem(x, y) { - var offset; - if (this.orientation === _UI.Orientation.horizontal) { - offset = x; - } else { - offset = y; - } - - this._measure(); - offset = offset + this._scrollPosition; - this._currentIndexForSezo = this._sectionSizes.length - 1; - for (var i = 1; i < this._sectionSizes.length; i++) { - var sectionSize = this._sectionSizes[i]; - if (sectionSize.offset - sectionSize.marginStart > offset) { - this._currentIndexForSezo = i - 1; - break; - } - } - }, - _getCurrentItem: function hub_getCurrentItem() { - var itemPosition; - if (this._sectionSizes.length > 0) { - this._measure(); - var index = Math.max(0, Math.min(this._currentIndexForSezo, this._sectionSizes.length)); - var sectionSize = this._sectionSizes[index]; - if (this.orientation === _UI.Orientation.horizontal) { - itemPosition = { - left: Math.max(0, sectionSize.offset - sectionSize.marginStart - this._scrollPosition), - top: 0, - width: sectionSize.size, - height: this._viewportOppositeSize - }; - } else { - itemPosition = { - left: 0, - top: Math.max(0, sectionSize.offset - sectionSize.marginStart - this._scrollPosition), - width: this._viewportOppositeSize, - height: sectionSize.size, - }; - } - - var section = this.sections.getAt(index); - // BUGBUG: 53301 ListView and Hub should document what they expect to be returned from the - // getCurrentItem so that positionItem apis line up. ListView zoomed out expects an object with - // groupIndexHint, groupKey, or groupDescription. Hub expects an object with index. - return Promise.wrap({ item: { data: section, index: index, groupIndexHint: index }, position: itemPosition }); - } - }, - _beginZoom: function hub_beginZoom() { - // Hide scroll thumb. - this._viewportElement.style["-ms-overflow-style"] = "none"; - }, - _positionItem: function hub_positionItem(item, position) { - if (item.index >= 0 && item.index < this._sectionSizes.length) { - this._measure(); - var sectionSize = this._sectionSizes[item.index]; - - var offsetFromViewport; - if (this.orientation === _UI.Orientation.horizontal) { - offsetFromViewport = position.left; - } else { - offsetFromViewport = position.top; - } - - this._sectionToFocus = item.index; - - var targetScrollPosition = sectionSize.offset - offsetFromViewport; - // clamp section: - var targetScrollPosition = this._ensureVisibleMath(item.index, targetScrollPosition); - - this._scrollPosition = targetScrollPosition; - var newScrollPos = {}; - newScrollPos[this._names.scrollPos] = this._scrollPosition; - _ElementUtilities.setScrollPosition(this._viewportElement, newScrollPos); - } - }, - _endZoom: function hub_endZoom() { - // Show scroll thumb. - this._viewportElement.style["-ms-overflow-style"] = ""; - }, - _writeProfilerMark: function hub_writeProfilerMark(text) { - var message = "WinJS.UI.Hub:" + this._id + ":" + text; - _WriteProfilerMark(message); - _Log.log && _Log.log(message, null, "hubprofiler"); - }, - dispose: function hub_dispose() { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - - _Global.removeEventListener('keydown', this._windowKeyDownHandlerBound); - _ElementUtilities._resizeNotifier.unsubscribe(this.element, this._resizeHandlerBound); - - this._updateEvents(this._sections); - - for (var i = 0; i < this.sections.length; i++) { - this.sections.getAt(i).dispose(); - } - } - }, { - /// - /// Specifies whether the Hub animation is an entrance animation or a transition animation. - /// - /// - AnimationType: { - /// - /// The animation plays when the Hub is first displayed. - /// - /// - entrance: "entrance", - /// - /// The animation plays when the Hub is changing its content. - /// - /// - contentTransition: "contentTransition", - /// - /// The animation plays when a section is inserted into the Hub. - /// - /// - insert: "insert", - /// - /// The animation plays when a section is removed into the Hub. - /// - /// - remove: "remove", - }, - /// - /// Gets the current loading state of the Hub. - /// - /// - LoadingState: { - /// - /// The Hub is loading sections. - /// - /// - loading: "loading", - /// - /// All sections are loaded and animations are complete. - /// - /// - complete: "complete" - }, - // Names of classes used by the Hub. - _ClassName: { - hub: "win-hub", - hubSurface: "win-hub-surface", - hubProgress: "win-hub-progress", - hubViewport: "win-hub-viewport", - hubVertical: "win-hub-vertical", - hubHorizontal: "win-hub-horizontal", - }, - // Names of events fired by the Hub. - _EventName: { - contentAnimating: eventNames.contentAnimating, - headerInvoked: eventNames.headerInvoked, - loadingStateChanged: eventNames.loadingStateChanged - }, - }); - - _Base.Class.mix(Hub, _Control.DOMEventMixin); - - var ZoomableView = _Base.Class.define(function ZoomableView_ctor(hub) { - this._hub = hub; - }, { - getPanAxis: function () { - return this._hub._getPanAxis(); - }, - configureForZoom: function (isZoomedOut, isCurrentView, triggerZoom, prefetchedPages) { - this._hub._configureForZoom(isZoomedOut, isCurrentView, triggerZoom, prefetchedPages); - }, - setCurrentItem: function (x, y) { - this._hub._setCurrentItem(x, y); - }, - getCurrentItem: function () { - return this._hub._getCurrentItem(); - }, - beginZoom: function () { - this._hub._beginZoom(); - }, - positionItem: function (item, position) { - return this._hub._positionItem(item, position); - }, - endZoom: function (isCurrentView) { - this._hub._endZoom(isCurrentView); - } - }); - - var strings = { - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get duplicateSection() { return "Hub duplicate sections: Each HubSection must be unique"; }, - get invalidContent() { return "Invalid content: Hub content must be made up of HubSections."; }, - get hubViewportAriaLabel() { return _Resources._getWinJSString("ui/hubViewportAriaLabel").value; } - }; - - return Hub; - }) - }); - -}); - -define('require-style!less/styles-lightdismissservice',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -var __extends = this.__extends || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -define('WinJS/_LightDismissService',["require", "exports", './Application', './Core/_Base', './Core/_BaseUtils', './Utilities/_ElementUtilities', './Core/_Global', './Utilities/_KeyboardBehavior', './Core/_Log', './Core/_Resources'], function (require, exports, Application, _Base, _BaseUtils, _ElementUtilities, _Global, _KeyboardBehavior, _Log, _Resources) { - require(["require-style!less/styles-lightdismissservice"]); - "use strict"; - var baseZIndex = 1000; - var Strings = { - get closeOverlay() { - return _Resources._getWinJSString("ui/closeOverlay").value; - } - }; - exports._ClassNames = { - _clickEater: "win-clickeater" - }; - var EventNames = { - requestingFocusOnKeyboardInput: "requestingfocusonkeyboardinput" - }; - exports.LightDismissalReasons = { - tap: "tap", - lostFocus: "lostFocus", - escape: "escape", - hardwareBackButton: "hardwareBackButton", - windowResize: "windowResize", - windowBlur: "windowBlur" - }; - // Built-in implementations of ILightDismissable's onShouldLightDismiss. - exports.DismissalPolicies = { - light: function LightDismissalPolicies_light_onShouldLightDismiss(info) { - switch (info.reason) { - case exports.LightDismissalReasons.tap: - case exports.LightDismissalReasons.escape: - if (info.active) { - return true; - } - else { - info.stopPropagation(); - return false; - } - break; - case exports.LightDismissalReasons.hardwareBackButton: - if (info.active) { - info.preventDefault(); // prevent backwards navigation in the app - return true; - } - else { - info.stopPropagation(); - return false; - } - break; - case exports.LightDismissalReasons.lostFocus: - case exports.LightDismissalReasons.windowResize: - case exports.LightDismissalReasons.windowBlur: - return true; - } - }, - modal: function LightDismissalPolicies_modal_onShouldLightDismiss(info) { - // Light dismiss cues should not be seen by dismissables behind the modal - info.stopPropagation(); - switch (info.reason) { - case exports.LightDismissalReasons.tap: - case exports.LightDismissalReasons.lostFocus: - case exports.LightDismissalReasons.windowResize: - case exports.LightDismissalReasons.windowBlur: - return false; - break; - case exports.LightDismissalReasons.escape: - return info.active; - break; - case exports.LightDismissalReasons.hardwareBackButton: - info.preventDefault(); // prevent backwards navigation in the app - return info.active; - break; - } - }, - sticky: function LightDismissalPolicies_sticky_onShouldLightDismiss(info) { - info.stopPropagation(); - return false; - } - }; - var KeyboardInfoType = { - keyDown: "keyDown", - keyUp: "keyUp", - keyPress: "keyPress" - }; - var AbstractDismissableElement = (function () { - function AbstractDismissableElement(args) { - this.element = args.element; - this.element.tabIndex = args.tabIndex; - this.onLightDismiss = args.onLightDismiss; - // Allow the caller to override the default implementations of our ILightDismissable methods. - if (args.onTakeFocus) { - this.onTakeFocus = args.onTakeFocus; - } - if (args.onShouldLightDismiss) { - this.onShouldLightDismiss = args.onShouldLightDismiss; - } - this._ldeOnKeyDownBound = this._ldeOnKeyDown.bind(this); - this._ldeOnKeyUpBound = this._ldeOnKeyUp.bind(this); - this._ldeOnKeyPressBound = this._ldeOnKeyPress.bind(this); - } - AbstractDismissableElement.prototype.restoreFocus = function () { - var activeElement = _Global.document.activeElement; - if (activeElement && this.containsElement(activeElement)) { - this._ldeCurrentFocus = activeElement; - return true; - } - else { - // If the last input type was keyboard, use focus() so a keyboard focus visual is drawn. - // Otherwise, use setActive() so no focus visual is drawn. - var useSetActive = !_KeyboardBehavior._keyboardSeenLast; - return this._ldeCurrentFocus && this.containsElement(this._ldeCurrentFocus) && _ElementUtilities._tryFocusOnAnyElement(this._ldeCurrentFocus, useSetActive); - } - }; - AbstractDismissableElement.prototype._ldeOnKeyDown = function (eventObject) { - this._ldeService.keyDown(this, eventObject); - }; - AbstractDismissableElement.prototype._ldeOnKeyUp = function (eventObject) { - this._ldeService.keyUp(this, eventObject); - }; - AbstractDismissableElement.prototype._ldeOnKeyPress = function (eventObject) { - this._ldeService.keyPress(this, eventObject); - }; - // ILightDismissable - // - AbstractDismissableElement.prototype.setZIndex = function (zIndex) { - this.element.style.zIndex = zIndex; - }; - AbstractDismissableElement.prototype.getZIndexCount = function () { - return 1; - }; - AbstractDismissableElement.prototype.containsElement = function (element) { - return this.element.contains(element); - }; - AbstractDismissableElement.prototype.onTakeFocus = function (useSetActive) { - this.restoreFocus() || _ElementUtilities._focusFirstFocusableElement(this.element, useSetActive) || _ElementUtilities._tryFocusOnAnyElement(this.element, useSetActive); - }; - AbstractDismissableElement.prototype.onFocus = function (element) { - this._ldeCurrentFocus = element; - }; - AbstractDismissableElement.prototype.onShow = function (service) { - this._ldeService = service; - this.element.addEventListener("keydown", this._ldeOnKeyDownBound); - this.element.addEventListener("keyup", this._ldeOnKeyUpBound); - this.element.addEventListener("keypress", this._ldeOnKeyPressBound); - }; - AbstractDismissableElement.prototype.onHide = function () { - this._ldeCurrentFocus = null; - this._ldeService = null; - this.element.removeEventListener("keydown", this._ldeOnKeyDownBound); - this.element.removeEventListener("keyup", this._ldeOnKeyUpBound); - this.element.removeEventListener("keypress", this._ldeOnKeyPressBound); - }; - // Concrete subclasses are expected to implement these. - AbstractDismissableElement.prototype.onKeyInStack = function (info) { - }; - AbstractDismissableElement.prototype.onShouldLightDismiss = function (info) { - return false; - }; - // Consumers of concrete subclasses of AbstractDismissableElement are expected to - // provide these as parameters to the constructor. - AbstractDismissableElement.prototype.onLightDismiss = function (info) { - }; - return AbstractDismissableElement; - })(); - var LightDismissableElement = (function (_super) { - __extends(LightDismissableElement, _super); - function LightDismissableElement() { - _super.apply(this, arguments); - } - LightDismissableElement.prototype.onKeyInStack = function (info) { - }; - LightDismissableElement.prototype.onShouldLightDismiss = function (info) { - return exports.DismissalPolicies.light(info); - }; - return LightDismissableElement; - })(AbstractDismissableElement); - exports.LightDismissableElement = LightDismissableElement; - var ModalElement = (function (_super) { - __extends(ModalElement, _super); - function ModalElement() { - _super.apply(this, arguments); - } - ModalElement.prototype.onKeyInStack = function (info) { - // stopPropagation so that none of the app's other event handlers will see the event. - // Don't preventDefault so that the browser's hotkeys will still work. - info.stopPropagation(); - }; - ModalElement.prototype.onShouldLightDismiss = function (info) { - return exports.DismissalPolicies.modal(info); - }; - return ModalElement; - })(AbstractDismissableElement); - exports.ModalElement = ModalElement; - // An implementation of ILightDismissable that represents the HTML body element. It can never be dismissed. The - // service should instantiate one of these to act as the bottommost light dismissable at all times (it isn't expected - // for anybody else to instantiate one). It takes care of restoring focus when the last dismissable is dismissed. - var LightDismissableBody = (function () { - function LightDismissableBody() { - } - LightDismissableBody.prototype.setZIndex = function (zIndex) { - }; - LightDismissableBody.prototype.getZIndexCount = function () { - return 1; - }; - LightDismissableBody.prototype.containsElement = function (element) { - return _Global.document.body.contains(element); - }; - LightDismissableBody.prototype.onTakeFocus = function (useSetActive) { - this.currentFocus && this.containsElement(this.currentFocus) && _ElementUtilities._tryFocusOnAnyElement(this.currentFocus, useSetActive); - }; - LightDismissableBody.prototype.onFocus = function (element) { - this.currentFocus = element; - }; - LightDismissableBody.prototype.onShow = function (service) { - }; - LightDismissableBody.prototype.onHide = function () { - this.currentFocus = null; - }; - LightDismissableBody.prototype.onKeyInStack = function (info) { - }; - LightDismissableBody.prototype.onShouldLightDismiss = function (info) { - return false; - }; - LightDismissableBody.prototype.onLightDismiss = function (info) { - }; - return LightDismissableBody; - })(); - ; - var LightDismissService = (function () { - function LightDismissService() { - this._debug = false; // Disables dismiss due to window blur. Useful during debugging. - this._clients = []; - this._notifying = false; - this._bodyClient = new LightDismissableBody(); - // State private to _updateDom. No other method should make use of it. - this._updateDom_rendered = { - serviceActive: false - }; - this._clickEaterEl = this._createClickEater(); - this._onBeforeRequestingFocusOnKeyboardInputBound = this._onBeforeRequestingFocusOnKeyboardInput.bind(this); - this._onFocusInBound = this._onFocusIn.bind(this); - this._onKeyDownBound = this._onKeyDown.bind(this); - this._onWindowResizeBound = this._onWindowResize.bind(this); - this._onClickEaterPointerUpBound = this._onClickEaterPointerUp.bind(this); - this._onClickEaterPointerCancelBound = this._onClickEaterPointerCancel.bind(this); - // Register for infrequent events. - Application.addEventListener("backclick", this._onBackClick.bind(this)); - // Focus handlers generally use _ElementUtilities._addEventListener with focusout/focusin. This - // uses the browser's blur event directly beacuse _addEventListener doesn't support focusout/focusin - // on window. - _Global.window.addEventListener("blur", this._onWindowBlur.bind(this)); - this.shown(this._bodyClient); - } - // Dismissables should call this as soon as they are ready to be shown. More specifically, they should call this: - // - After they are in the DOM and ready to receive focus (e.g. style.display cannot = "none") - // - Before their entrance animation is played - LightDismissService.prototype.shown = function (client) { - var index = this._clients.indexOf(client); - if (index === -1) { - this._clients.push(client); - client.onShow(this); - this._updateDom(); - } - }; - // Dismissables should call this when they are done being dismissed (i.e. after their exit animation has finished) - LightDismissService.prototype.hidden = function (client) { - var index = this._clients.indexOf(client); - if (index !== -1) { - this._clients.splice(index, 1); - client.setZIndex(""); - client.onHide(); - this._updateDom(); - } - }; - // Dismissables should call this when their state has changed such that it'll affect the behavior of some method - // in its ILightDismissable interface. For example, if the dismissable was altered such that getZIndexCount will - // now return 2 instead of 1, that dismissable should call *updated* so the LightDismissService can find out about - // this change. - LightDismissService.prototype.updated = function (client) { - this._updateDom(); - }; - LightDismissService.prototype.keyDown = function (client, eventObject) { - if (eventObject.keyCode === _ElementUtilities.Key.escape) { - this._escapePressed(eventObject); - } - else { - this._dispatchKeyboardEvent(client, KeyboardInfoType.keyDown, eventObject); - } - }; - LightDismissService.prototype.keyUp = function (client, eventObject) { - this._dispatchKeyboardEvent(client, KeyboardInfoType.keyUp, eventObject); - }; - LightDismissService.prototype.keyPress = function (client, eventObject) { - this._dispatchKeyboardEvent(client, KeyboardInfoType.keyPress, eventObject); - }; - LightDismissService.prototype.isShown = function (client) { - return this._clients.indexOf(client) !== -1; - }; - LightDismissService.prototype.isTopmost = function (client) { - return client === this._clients[this._clients.length - 1]; - }; - // Disables dismiss due to window blur. Useful during debugging. - LightDismissService.prototype._setDebug = function (debug) { - this._debug = debug; - }; - LightDismissService.prototype._updateDom = function (options) { - options = options || {}; - var activeDismissableNeedsFocus = !!options.activeDismissableNeedsFocus; - var rendered = this._updateDom_rendered; - if (this._notifying) { - return; - } - var serviceActive = this._clients.length > 1; - if (serviceActive !== rendered.serviceActive) { - // Unregister/register for events that occur frequently. - if (serviceActive) { - Application.addEventListener("beforerequestingfocusonkeyboardinput", this._onBeforeRequestingFocusOnKeyboardInputBound); - _ElementUtilities._addEventListener(_Global.document.documentElement, "focusin", this._onFocusInBound); - _Global.document.documentElement.addEventListener("keydown", this._onKeyDownBound); - _Global.window.addEventListener("resize", this._onWindowResizeBound); - this._bodyClient.currentFocus = _Global.document.activeElement; - _Global.document.body.appendChild(this._clickEaterEl); - } - else { - Application.removeEventListener("beforerequestingfocusonkeyboardinput", this._onBeforeRequestingFocusOnKeyboardInputBound); - _ElementUtilities._removeEventListener(_Global.document.documentElement, "focusin", this._onFocusInBound); - _Global.document.documentElement.removeEventListener("keydown", this._onKeyDownBound); - _Global.window.removeEventListener("resize", this._onWindowResizeBound); - var parent = this._clickEaterEl.parentNode; - parent && parent.removeChild(this._clickEaterEl); - } - rendered.serviceActive = serviceActive; - } - var zIndexGap = 0; - var lastUsedZIndex = baseZIndex + 1; - this._clients.forEach(function (c, i) { - var currentZIndex = lastUsedZIndex + zIndexGap; - c.setZIndex("" + currentZIndex); - lastUsedZIndex = currentZIndex; - // count + 1 so that there's an unused zIndex between each pair of - // dismissables that can be used by the click eater. - zIndexGap = c.getZIndexCount() + 1; - }); - if (serviceActive) { - this._clickEaterEl.style.zIndex = "" + (lastUsedZIndex - 1); - } - var activeDismissable = this._clients.length > 0 ? this._clients[this._clients.length - 1] : null; - if (this._activeDismissable !== activeDismissable) { - this._activeDismissable = activeDismissable; - activeDismissableNeedsFocus = true; - } - if (activeDismissableNeedsFocus) { - // If the last input type was keyboard, use focus() so a keyboard focus visual is drawn. - // Otherwise, use setActive() so no focus visual is drawn. - var useSetActive = !_KeyboardBehavior._keyboardSeenLast; - this._activeDismissable && this._activeDismissable.onTakeFocus(useSetActive); - } - }; - LightDismissService.prototype._dispatchKeyboardEvent = function (client, keyboardInfoType, eventObject) { - var index = this._clients.indexOf(client); - if (index !== -1) { - var info = { - type: keyboardInfoType, - keyCode: eventObject.keyCode, - propagationStopped: false, - stopPropagation: function () { - this.propagationStopped = true; - eventObject.stopPropagation(); - } - }; - var clients = this._clients.slice(0, index + 1); - for (var i = clients.length - 1; i >= 0 && !info.propagationStopped; i--) { - clients[i].onKeyInStack(info); - } - } - }; - LightDismissService.prototype._dispatchLightDismiss = function (reason, clients, options) { - if (this._notifying) { - _Log.log && _Log.log('_LightDismissService ignored dismiss trigger to avoid re-entrancy: "' + reason + '"', "winjs _LightDismissService", "warning"); - return; - } - clients = clients || this._clients.slice(0); - if (clients.length === 0) { - return; - } - this._notifying = true; - var lightDismissInfo = { - // Which of the LightDismissalReasons caused this event to fire? - reason: reason, - // Is this dismissable currently the active dismissable? - active: false, - _stop: false, - stopPropagation: function () { - this._stop = true; - }, - _doDefault: true, - preventDefault: function () { - this._doDefault = false; - } - }; - for (var i = clients.length - 1; i >= 0 && !lightDismissInfo._stop; i--) { - lightDismissInfo.active = this._activeDismissable === clients[i]; - if (clients[i].onShouldLightDismiss(lightDismissInfo)) { - clients[i].onLightDismiss(lightDismissInfo); - } - } - this._notifying = false; - this._updateDom(options); - return lightDismissInfo._doDefault; - }; - LightDismissService.prototype._onBeforeRequestingFocusOnKeyboardInput = function (eventObject) { - // Suppress the requestingFocusOnKeyboardInput event. - return true; - }; - // - // Light dismiss triggers - // - // Called by tests. - LightDismissService.prototype._clickEaterTapped = function () { - this._dispatchLightDismiss(exports.LightDismissalReasons.tap); - }; - LightDismissService.prototype._onFocusIn = function (eventObject) { - var target = eventObject.target; - for (var i = this._clients.length - 1; i >= 0; i--) { - if (this._clients[i].containsElement(target)) { - break; - } - } - if (i !== -1) { - this._clients[i].onFocus(target); - } - if (i + 1 < this._clients.length) { - this._dispatchLightDismiss(exports.LightDismissalReasons.lostFocus, this._clients.slice(i + 1), { - activeDismissableNeedsFocus: true - }); - } - }; - LightDismissService.prototype._onKeyDown = function (eventObject) { - if (eventObject.keyCode === _ElementUtilities.Key.escape) { - this._escapePressed(eventObject); - } - }; - LightDismissService.prototype._escapePressed = function (eventObject) { - eventObject.preventDefault(); - eventObject.stopPropagation(); - this._dispatchLightDismiss(exports.LightDismissalReasons.escape); - }; - // Called by tests. - LightDismissService.prototype._onBackClick = function (eventObject) { - var doDefault = this._dispatchLightDismiss(exports.LightDismissalReasons.hardwareBackButton); - return !doDefault; // Returns whether or not the event was handled. - }; - LightDismissService.prototype._onWindowResize = function (eventObject) { - this._dispatchLightDismiss(exports.LightDismissalReasons.windowResize); - }; - LightDismissService.prototype._onWindowBlur = function (eventObject) { - if (this._debug) { - return; - } - // Want to trigger a light dismiss on window blur. - // We get blur if we click off the window, including into an iframe within our window. - // Both blurs call this function, but fortunately document.hasFocus is true if either - // the document window or our iframe window has focus. - if (!_Global.document.hasFocus()) { - // The document doesn't have focus, so they clicked off the app, so light dismiss. - this._dispatchLightDismiss(exports.LightDismissalReasons.windowBlur); - } - else { - // We were trying to unfocus the window, but document still has focus, - // so make sure the iframe that took the focus will check for blur next time. - var active = _Global.document.activeElement; - if (active && active.tagName === "IFRAME" && !active["msLightDismissBlur"]) { - // - This will go away when the IFRAME goes away, and we only create one. - // - This only works in IE because other browsers don't fire focus events on iframe elements. - // - Can't use _ElementUtilities._addEventListener's focusout because it doesn't fire when an - // iframe loses focus due to changing windows. - active.addEventListener("blur", this._onWindowBlur.bind(this), false); - active["msLightDismissBlur"] = true; - } - } - }; - LightDismissService.prototype._createClickEater = function () { - var clickEater = _Global.document.createElement("section"); - clickEater.className = exports._ClassNames._clickEater; - _ElementUtilities._addEventListener(clickEater, "pointerdown", this._onClickEaterPointerDown.bind(this), true); - clickEater.addEventListener("click", this._onClickEaterClick.bind(this), true); - // Tell Aria that it's clickable - clickEater.setAttribute("role", "menuitem"); - clickEater.setAttribute("aria-label", Strings.closeOverlay); - // Prevent CED from removing any current selection - clickEater.setAttribute("unselectable", "on"); - return clickEater; - }; - LightDismissService.prototype._onClickEaterPointerDown = function (eventObject) { - eventObject.stopPropagation(); - eventObject.preventDefault(); - this._clickEaterPointerId = eventObject.pointerId; - if (!this._registeredClickEaterCleanUp) { - _ElementUtilities._addEventListener(_Global.window, "pointerup", this._onClickEaterPointerUpBound); - _ElementUtilities._addEventListener(_Global.window, "pointercancel", this._onClickEaterPointerCancelBound); - this._registeredClickEaterCleanUp = true; - } - }; - LightDismissService.prototype._onClickEaterPointerUp = function (eventObject) { - var _this = this; - eventObject.stopPropagation(); - eventObject.preventDefault(); - if (eventObject.pointerId === this._clickEaterPointerId) { - this._resetClickEaterPointerState(); - var element = _Global.document.elementFromPoint(eventObject.clientX, eventObject.clientY); - if (element === this._clickEaterEl) { - this._skipClickEaterClick = true; - _BaseUtils._yieldForEvents(function () { - _this._skipClickEaterClick = false; - }); - this._clickEaterTapped(); - } - } - }; - LightDismissService.prototype._onClickEaterClick = function (eventObject) { - eventObject.stopPropagation(); - eventObject.preventDefault(); - if (!this._skipClickEaterClick) { - // Handle the UIA invoke action on the click eater. this._skipClickEaterClick is false which tells - // us that we received a click event without an associated PointerUp event. This means that the click - // event was triggered thru UIA rather than thru the GUI. - this._clickEaterTapped(); - } - }; - LightDismissService.prototype._onClickEaterPointerCancel = function (eventObject) { - if (eventObject.pointerId === this._clickEaterPointerId) { - this._resetClickEaterPointerState(); - } - }; - LightDismissService.prototype._resetClickEaterPointerState = function () { - if (this._registeredClickEaterCleanUp) { - _ElementUtilities._removeEventListener(_Global.window, "pointerup", this._onClickEaterPointerUpBound); - _ElementUtilities._removeEventListener(_Global.window, "pointercancel", this._onClickEaterPointerCancelBound); - } - this._clickEaterPointerId = null; - this._registeredClickEaterCleanUp = false; - }; - return LightDismissService; - })(); - var service = new LightDismissService(); - exports.shown = service.shown.bind(service); - exports.hidden = service.hidden.bind(service); - exports.updated = service.updated.bind(service); - exports.isShown = service.isShown.bind(service); - exports.isTopmost = service.isTopmost.bind(service); - exports.keyDown = service.keyDown.bind(service); - exports.keyUp = service.keyUp.bind(service); - exports.keyPress = service.keyPress.bind(service); - exports._clickEaterTapped = service._clickEaterTapped.bind(service); - exports._onBackClick = service._onBackClick.bind(service); - exports._setDebug = service._setDebug.bind(service); - _Base.Namespace.define("WinJS.UI._LightDismissService", { - shown: exports.shown, - hidden: exports.hidden, - updated: exports.updated, - isShown: exports.isShown, - isTopmost: exports.isTopmost, - keyDown: exports.keyDown, - keyUp: exports.keyUp, - keyPress: exports.keyPress, - _clickEaterTapped: exports._clickEaterTapped, - _onBackClick: exports._onBackClick, - _setDebug: exports._setDebug, - LightDismissableElement: LightDismissableElement, - DismissalPolicies: exports.DismissalPolicies, - LightDismissalReasons: exports.LightDismissalReasons, - _ClassNames: exports._ClassNames, - _service: service - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/_LegacyAppBar/_Constants',[ - 'exports', - '../../Core/_Base', -], function appBarConstantsInit(exports, _Base) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, null, { - // AppBar class names. - appBarClass: "win-navbar", - firstDivClass: "win-firstdiv", - finalDivClass: "win-finaldiv", - invokeButtonClass: "win-navbar-invokebutton", - ellipsisClass: "win-navbar-ellipsis", - primaryCommandsClass: "win-primarygroup", - secondaryCommandsClass: "win-secondarygroup", - commandLayoutClass: "win-commandlayout", - menuLayoutClass: "win-menulayout", - topClass: "win-top", - bottomClass: "win-bottom", - showingClass : "win-navbar-opening", - shownClass : "win-navbar-opened", - hidingClass : "win-navbar-closing", - hiddenClass: "win-navbar-closed", - compactClass: "win-navbar-compact", - minimalClass: "win-navbar-minimal", - menuContainerClass: "win-navbar-menu", - - // Constants for AppBar placement - appBarPlacementTop: "top", - appBarPlacementBottom: "bottom", - - // Constants for AppBar layouts - appBarLayoutCustom: "custom", - appBarLayoutCommands: "commands", - appBarLayoutMenu: "menu", - - // Constant for AppBar invokebutton width - appBarInvokeButtonWidth: 32, - - // Constants for Commands - typeSeparator: "separator", - typeContent: "content", - typeButton: "button", - typeToggle: "toggle", - typeFlyout: "flyout", - appBarCommandClass: "win-command", - appBarCommandGlobalClass: "win-global", - appBarCommandSelectionClass: "win-selection", - sectionSelection: "selection", /* deprecated, use sectionSecondary */ - sectionGlobal: "global", /* deprecated, use sectionPrimary */ - sectionPrimary: "primary", - sectionSecondary: "secondary", - - // Constants for Menus - menuCommandClass: "win-command", - menuCommandButtonClass: "win-command-button", - menuCommandToggleClass: "win-command-toggle", - menuCommandFlyoutClass: "win-command-flyout", - menuCommandFlyoutActivatedClass: "win-command-flyout-activated", - menuCommandSeparatorClass: "win-command-separator", - _menuCommandInvokedEvent: "_invoked", // Private event - menuClass: "win-menu", - menuContainsToggleCommandClass: "win-menu-containstogglecommand", - menuContainsFlyoutCommandClass: "win-menu-containsflyoutcommand", - menuMouseSpacingClass: "win-menu-mousespacing", - menuTouchSpacingClass: "win-menu-touchspacing", - menuCommandHoverDelay: 400, - - // Other class names - overlayClass: "win-overlay", - flyoutClass: "win-flyout", - flyoutLightClass: "win-ui-light", - settingsFlyoutClass: "win-settingsflyout", - scrollsClass: "win-scrolls", - pinToRightEdge: -1, - pinToBottomEdge: -1, - - // Constants for AppBarCommand full-size widths. - separatorWidth: 34, - buttonWidth: 68, - - narrowClass: "win-narrow", - wideClass: "win-wide", - _visualViewportClass: "win-visualviewport-space", - - // Event names - commandPropertyMutated: "_commandpropertymutated", - commandVisibilityChanged: "commandvisibilitychanged", - }); -}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Utilities/_KeyboardInfo',["require", "exports", '../Core/_BaseCoreUtils', '../Core/_Global', '../Core/_WinRT'], function (require, exports, _BaseCoreUtils, _Global, _WinRT) { - "use strict"; - var _Constants = { - visualViewportClass: "win-visualviewport-space", - scrollTimeout: 150, - }; - // This private module provides accurate metrics for the Visual Viewport and WWA's IHM offsets in Win10 WWA - // where "-ms-device-fixed" CSS positioning is supported. WinJS controls will also use this module for - // positoning themselves relative to the viewport in a web browser outside of WWA. Their preference is still - // to rely on "-ms-device-fixed" positioning, but currently fallback to "fixed" positioning in enviornments where - // "-ms-device-fixed" is not supported. - exports._KeyboardInfo; - // WWA Soft Keyboard offsets - exports._KeyboardInfo = { - // Determine if the keyboard is visible or not. - get _visible() { - try { - return (_WinRT.Windows.UI.ViewManagement.InputPane && _WinRT.Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height > 0); - } - catch (e) { - return false; - } - }, - // See if we have to reserve extra space for the IHM - get _extraOccluded() { - var occluded = 0; - // Controls using -ms-device-fixed positioning only need to reposition themselves to remain visible - // If the IHM has not resized the viewport. - if (!exports._KeyboardInfo._isResized && _WinRT.Windows.UI.ViewManagement.InputPane) { - occluded = _WinRT.Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height; - } - return occluded; - }, - // See if the view has been resized to fit a keyboard - get _isResized() { - // Compare ratios. Very different includes IHM space. - var heightRatio = _Global.document.documentElement.clientHeight / _Global.innerHeight, widthRatio = _Global.document.documentElement.clientWidth / _Global.innerWidth; - // If they're nearly identical, then the view hasn't been resized for the IHM - // Only check one bound because we know the IHM will make it shorter, not skinnier. - return (widthRatio / heightRatio < 0.99); - }, - // Get the bottom of the visible area, relative to the top edge of the visible area. - get _visibleDocBottom() { - return exports._KeyboardInfo._visibleDocTop + exports._KeyboardInfo._visibleDocHeight; - }, - // Get the height of the visible area, e.g. the height of the visual viewport minus any IHM occlusion. - get _visibleDocHeight() { - return exports._KeyboardInfo._visualViewportHeight - exports._KeyboardInfo._extraOccluded; - }, - // Get the top offset of our visible area, aka the top of the visual viewport. - // This is always 0 when elements use -ms-device-fixed positioning. - get _visibleDocTop() { - return 0; - }, - // Get the offset for, and relative to, the bottom edge of the visual viewport plus any IHM occlusion. - get _visibleDocBottomOffset() { - // For -ms-device-fixed positioned elements, the bottom is just 0 when there's no IHM. - // When the IHM appears, the text input that invoked it may be in a position on the page that is occluded by the IHM. - // In that instance, the default browser behavior is to resize the visual viewport and scroll the input back into view. - // However, if the viewport resize is prevented by an IHM event listener, the keyboard will still occlude - // -ms-device-fixed elements, so we adjust the bottom offset of the appbar by the height of the occluded rect of the IHM. - return exports._KeyboardInfo._extraOccluded; - }, - // Get the visual viewport height. window.innerHeight doesn't return floating point values which are present with high DPI. - get _visualViewportHeight() { - var boundingRect = exports._KeyboardInfo._visualViewportSpace; - return boundingRect.height; - }, - // Get the visual viewport width. window.innerWidth doesn't return floating point values which are present with high DPI. - get _visualViewportWidth() { - var boundingRect = exports._KeyboardInfo._visualViewportSpace; - return boundingRect.width; - }, - // The visual viewport space element is hidden given -ms-device-fixed positioning and used to calculate - // the 4 edges of the visual viewport with floating point precision. - get _visualViewportSpace() { - var visualViewportSpace = _Global.document.body.querySelector("." + _Constants.visualViewportClass); - if (!visualViewportSpace) { - visualViewportSpace = _Global.document.createElement("DIV"); - visualViewportSpace.className = _Constants.visualViewportClass; - _Global.document.body.appendChild(visualViewportSpace); - } - return visualViewportSpace.getBoundingClientRect(); - }, - // Get total length of the IHM showPanel animation - get _animationShowLength() { - if (_BaseCoreUtils.hasWinRT) { - if (_WinRT.Windows.UI.Core.AnimationMetrics) { - // Desktop exposes the AnimationMetrics API that allows us to look up the relevant IHM animation metrics. - var a = _WinRT.Windows.UI.Core.AnimationMetrics, animationDescription = new a.AnimationDescription(a.AnimationEffect.showPanel, a.AnimationEffectTarget.primary); - var animations = animationDescription.animations; - var max = 0; - for (var i = 0; i < animations.size; i++) { - var animation = animations[i]; - max = Math.max(max, animation.delay + animation.duration); - } - return max; - } - else { - // Phone platform does not yet expose the Animation Metrics API. - // Hard code the correct values for the time being. - // https://github.com/winjs/winjs/issues/1060 - var animationDuration = 300; - var animationDelay = 50; - return animationDelay + animationDuration; - } - } - else { - return 0; - } - }, - // Padding for IHM timer to allow for first scroll event. Tpyically used in conjunction with the - // _animationShowLength to determine the length of time in which a showing IHM would have triggered - // a window resize to occur. - get _scrollTimeout() { - return _Constants.scrollTimeout; - }, - // _layoutViewportCoords is used with elements that use position:fixed instead of position:-ms-device-fixed - get _layoutViewportCoords() { - var topOffset = _Global.window.pageYOffset - _Global.document.documentElement.scrollTop; - var bottomOffset = _Global.document.documentElement.clientHeight - (topOffset + this._visibleDocHeight); - return { - visibleDocTop: topOffset, - visibleDocBottom: bottomOffset - }; - } - }; -}); - - -define('require-style!less/styles-overlay',[],function(){}); - -define('require-style!less/colors-overlay',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// animatable,appbar,appbars,divs,Flyout,Flyouts,iframe,Statics,unfocus,unselectable -define('WinJS/Controls/Flyout/_Overlay',[ - 'exports', - '../../Core/_Global', - '../../Core/_WinRT', - '../../Core/_Base', - '../../Core/_BaseUtils', - '../../Core/_ErrorFromName', - '../../Core/_Events', - '../../Core/_Resources', - '../../Core/_WriteProfilerMark', - '../../_Accents', - '../../Animations', - '../../Application', - '../../ControlProcessor', - '../../Promise', - '../../Scheduler', - '../../Utilities/_Control', - '../../Utilities/_ElementUtilities', - '../../Utilities/_KeyboardInfo', - '../_LegacyAppBar/_Constants', - 'require-style!less/styles-overlay', - 'require-style!less/colors-overlay' -], function overlayInit(exports, _Global, _WinRT, _Base, _BaseUtils, _ErrorFromName, _Events, _Resources, _WriteProfilerMark, _Accents, Animations, Application, ControlProcessor, Promise, Scheduler, _Control, _ElementUtilities, _KeyboardInfo, _Constants) { - "use strict"; - - _Accents.createAccentRule( - "button[aria-checked=true].win-command:before,\ - .win-menu-containsflyoutcommand button.win-command-flyout-activated:before", [ - { name: "background-color", value: _Accents.ColorTypes.accent }, - { name: "border-color", value: _Accents.ColorTypes.accent }, - ]); - - _Accents.createAccentRule(".win-flyout, .win-settingsflyout", [{ name: "border-color", value: _Accents.ColorTypes.accent }]); - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - _Overlay: _Base.Namespace._lazy(function () { - - // Helper for Global Event listeners. Invokes the specified callback member function on each _Overlay in the DOM. - function _allOverlaysCallback(event, nameOfFunctionCall, stopImmediatePropagationWhenHandled) { - var elements = _Global.document.querySelectorAll("." + _Constants.overlayClass); - if (elements) { - var len = elements.length; - for (var i = 0; i < len; i++) { - var element = elements[i]; - var overlay = element.winControl; - if (!overlay._disposed) { - if (overlay) { - var handled = overlay[nameOfFunctionCall](event); - if (stopImmediatePropagationWhenHandled && handled) { - // The caller has indicated we should exit as soon as the event is handled. - return handled; - } - } - } - } - } - } - - // _Overlay Global Events Listener Class. We hang a singleton instance of this class off of a static _Overlay property. - var _GlobalListener = _Base.Class.define(function _GlobalListener_ctor() { - this._currentState = _GlobalListener.states.off; - - this._inputPaneShowing = this._inputPaneShowing.bind(this); - this._inputPaneHiding = this._inputPaneHiding.bind(this); - this._documentScroll = this._documentScroll.bind(this); - this._windowResized = this._windowResized.bind(this); - }, { - initialize: function _GlobalListener_initialize() { - this._toggleListeners(_GlobalListener.states.on); - }, - // Expose this for unit tests. - reset: function _GlobalListener_reset() { - this._toggleListeners(_GlobalListener.states.off); - this._toggleListeners(_GlobalListener.states.on); - }, - _inputPaneShowing: function _GlobalListener_inputePaneShowing(event) { - _WriteProfilerMark(_GlobalListener.profilerString + "_showingKeyboard,StartTM"); - _allOverlaysCallback(event, "_showingKeyboard"); - _WriteProfilerMark(_GlobalListener.profilerString + "_showingKeyboard,StopTM"); - }, - _inputPaneHiding: function _GlobalListener_inputPaneHiding(event) { - _WriteProfilerMark(_GlobalListener.profilerString + "_hidingKeyboard,StartTM"); - _allOverlaysCallback(event, "_hidingKeyboard"); - _WriteProfilerMark(_GlobalListener.profilerString + "_hidingKeyboard,StopTM"); - }, - _documentScroll: function _GlobalListener_documentScroll(event) { - _WriteProfilerMark(_GlobalListener.profilerString + "_checkScrollPosition,StartTM"); - _allOverlaysCallback(event, "_checkScrollPosition"); - _WriteProfilerMark(_GlobalListener.profilerString + "_checkScrollPosition,StopTM"); - }, - _windowResized: function _GlobalListener_windowResized(event) { - _WriteProfilerMark(_GlobalListener.profilerString + "_baseResize,StartTM"); - _allOverlaysCallback(event, "_baseResize"); - _WriteProfilerMark(_GlobalListener.profilerString + "_baseResize,StopTM"); - }, - _toggleListeners: function _GlobalListener_toggleListeners(newState) { - // Add/Remove global event listeners for all _Overlays - var listenerOperation; - if (this._currentState !== newState) { - if (newState === _GlobalListener.states.on) { - listenerOperation = "addEventListener"; - } else if (newState === _GlobalListener.states.off) { - listenerOperation = "removeEventListener"; - } - - if (_WinRT.Windows.UI.ViewManagement.InputPane) { - // React to Soft Keyboard events - var inputPane = _WinRT.Windows.UI.ViewManagement.InputPane.getForCurrentView(); - inputPane[listenerOperation]("showing", this._inputPaneShowing, false); - inputPane[listenerOperation]("hiding", this._inputPaneHiding, false); - - _Global.document[listenerOperation]("scroll", this._documentScroll, false); - } - - // Window resize event - _Global.addEventListener("resize", this._windowResized, false); - - this._currentState = newState; - } - }, - }, { - // Statics - profilerString: { - get: function () { - return "WinJS.UI._Overlay Global Listener:"; - } - }, - states: { - get: function () { - return { - off: 0, - on: 1, - }; - }, - }, - }); - - // Helper to get DOM elements from input single object or array or IDs/toolkit/dom elements - function _resolveElements(elements) { - // No input is just an empty array - if (!elements) { - return []; - } - - // Make sure it's in array form. - if (typeof elements === "string" || !elements || !elements.length) { - elements = [elements]; - } - - // Make sure we have a DOM element for each one, (could be string id name or toolkit object) - var i, - realElements = []; - for (i = 0; i < elements.length; i++) { - if (elements[i]) { - if (typeof elements[i] === "string") { - var element = _Global.document.getElementById(elements[i]); - if (element) { - realElements.push(element); - } - } else if (elements[i].element) { - realElements.push(elements[i].element); - } else { - realElements.push(elements[i]); - } - } - } - - return realElements; - } - - var strings = { - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get mustContainCommands() { return "Invalid HTML: AppBars/Menus must contain only AppBarCommands/MenuCommands"; }, - get closeOverlay() { return _Resources._getWinJSString("ui/closeOverlay").value; }, - }; - - var _Overlay = _Base.Class.define(function _Overlay_ctor(element, options) { - /// - /// - /// Constructs the Overlay control and associates it with the underlying DOM element. - /// - /// - /// The DOM element to be associated with the Overlay control. - /// - /// - /// The set of options to be applied initially to the Overlay control. - /// - /// A fully constructed Overlay control. - /// - this._baseOverlayConstructor(element, options); - }, { - // Functions/properties - _baseOverlayConstructor: function _Overlay_baseOverlayConstructor(element, options) { - - this._disposed = false; - - // Make sure there's an input element - if (!element) { - element = _Global.document.createElement("div"); - } - - // Check to make sure we weren't duplicated - var overlay = element.winControl; - if (overlay) { - throw new _ErrorFromName("WinJS.UI._Overlay.DuplicateConstruction", strings.duplicateConstruction); - } - - if (!this._element) { - this._element = element; - } - - if (!this._element.hasAttribute("tabIndex")) { - this._element.tabIndex = -1; - } - - this._sticky = false; - this._doNext = ""; - - this._element.style.visibility = "hidden"; - this._element.style.opacity = 0; - - // Remember ourselves - element.winControl = this; - - // Attach our css class - _ElementUtilities.addClass(this._element, _Constants.overlayClass); - _ElementUtilities.addClass(this._element, "win-disposable"); - - // We don't want to be selectable, set UNSELECTABLE - var unselectable = this._element.getAttribute("unselectable"); - if (unselectable === null || unselectable === undefined) { - this._element.setAttribute("unselectable", "on"); - } - - // Base animation is popIn/popOut - this._currentAnimateIn = this._baseAnimateIn; - this._currentAnimateOut = this._baseAnimateOut; - this._animationPromise = Promise.as(); - - // Command Animations to Queue - this._queuedToShow = []; - this._queuedToHide = []; - this._queuedCommandAnimation = false; - - if (options) { - _Control.setOptions(this, options); - } - - // Make sure _Overlay event handlers are hooked up (this aids light dismiss) - _Overlay._globalEventListeners.initialize(); - }, - - /// - element: { - get: function () { - return this._element; - } - }, - - dispose: function () { - /// - /// - /// Disposes this Overlay. - /// - /// - if (this._disposed) { - return; - } - - this._disposed = true; - this._dispose(); - }, - - _dispose: function _Overlay_dispose() { - // To be overridden by subclasses - }, - - _show: function _Overlay_show() { - // We call our base _baseShow because AppBar may need to override show - this._baseShow(); - }, - - _hide: function _Overlay_hide() { - // We call our base _baseHide because AppBar may need to override hide - this._baseHide(); - }, - - // Is the overlay "hidden"? - /// - hidden: { - get: function () { - return (this._element.style.visibility === "hidden" || - this._element.winAnimating === "hiding" || - this._doNext === "hide"); - }, - set: function (hidden) { - var currentlyHidden = this.hidden; - if (!hidden && currentlyHidden) { - this._show(); - } else if (hidden && !currentlyHidden) { - this._hide(); - } - } - }, - - addEventListener: function (type, listener, useCapture) { - /// - /// - /// Add an event listener to the DOM element for this Overlay - /// - /// Required. Event type to add, "beforehide", "afterhide", "beforeshow", or "aftershow" - /// Required. The event handler function to associate with this event. - /// Optional. True, register for the event capturing phase. False for the event bubbling phase. - /// - return this._element.addEventListener(type, listener, useCapture); - }, - - removeEventListener: function (type, listener, useCapture) { - /// - /// - /// Remove an event listener to the DOM element for this Overlay - /// - /// Required. Event type to remove, "beforehide", "afterhide", "beforeshow", or "aftershow" - /// Required. The event handler function to associate with this event. - /// Optional. True, register for the event capturing phase. False for the event bubbling phase. - /// - return this._element.removeEventListener(type, listener, useCapture); - }, - - _baseShow: function _Overlay_baseShow() { - // If we are already animating, just remember this for later - if (this._animating || this._needToHandleHidingKeyboard) { - this._doNext = "show"; - return false; - } - - if (this._element.style.visibility !== "visible") { - // Let us know we're showing. - this._element.winAnimating = "showing"; - - // Hiding, but not none - this._element.style.display = ""; - this._element.style.visibility = "hidden"; - - // In case their event is going to manipulate commands, see if there are - // any queued command animations we can handle while we're still hidden. - if (this._queuedCommandAnimation) { - this._showAndHideFast(this._queuedToShow, this._queuedToHide); - this._queuedToShow = []; - this._queuedToHide = []; - } - - // Send our "beforeShow" event - this._sendEvent(_Overlay.beforeShow); - - // Need to measure - this._findPosition(); - - // Make sure it's visible, and fully opaque. - // Do the popup thing, sending event afterward. - var that = this; - this._animationPromise = this._currentAnimateIn(). - then(function () { - that._baseEndShow(); - }, function () { - that._baseEndShow(); - }); - return true; - } - return false; - }, - - // Flyout in particular will need to measure our positioning. - _findPosition: function _Overlay_findPosition() { - }, - - _baseEndShow: function _Overlay_baseEndShow() { - if (this._disposed) { - return; - } - - // Make sure it's visible after showing - this._element.setAttribute("aria-hidden", "false"); - - this._element.winAnimating = ""; - - // Do our derived classes show stuff - this._endShow(); - - // We're shown now - if (this._doNext === "show") { - this._doNext = ""; - } - - // After showing, send the after showing event - this._sendEvent(_Overlay.afterShow); - this._writeProfilerMark("show,StopTM"); // Overlay writes the stop profiler mark for all of its derived classes. - - // If we had something queued, do that - Scheduler.schedule(this._checkDoNext, Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); - - }, - - _endShow: function _Overlay_endShow() { - // Nothing by default - }, - - _baseHide: function _Overlay_baseHide() { - // If we are already animating, just remember this for later - if (this._animating) { - this._doNext = "hide"; - return false; - } - - // In the unlikely event we're between the hiding keyboard and the resize events, just snap it away: - if (this._needToHandleHidingKeyboard) { - // use the "uninitialized" flag - this._element.style.visibility = ""; - } - - if (this._element.style.visibility !== "hidden") { - // Let us know we're hiding, accessibility as well. - this._element.winAnimating = "hiding"; - this._element.setAttribute("aria-hidden", "true"); - - // Send our "beforeHide" event - this._sendEvent(_Overlay.beforeHide); - - // If our visibility is empty, then this is the first time, just hide it - if (this._element.style.visibility === "") { - // Initial hiding, just hide it - this._element.style.opacity = 0; - this._baseEndHide(); - } else { - // Make sure it's hidden, and fully transparent. - var that = this; - this._animationPromise = this._currentAnimateOut(). - then(function () { - that._baseEndHide(); - }, function () { - that._baseEndHide(); - }); - } - return true; - } - - return false; - }, - - _baseEndHide: function _Overlay_baseEndHide() { - if (this._disposed) { - return; - } - - // Do our derived classes hide stuff - this._beforeEndHide(); - - // Make sure animation is finished. - this._element.style.visibility = "hidden"; - this._element.style.display = "none"; - this._element.winAnimating = ""; - - // In case their event is going to manipulate commands, see if there - // are any queued command animations we can handle now we're hidden. - if (this._queuedCommandAnimation) { - this._showAndHideFast(this._queuedToShow, this._queuedToHide); - this._queuedToShow = []; - this._queuedToHide = []; - } - - // We're hidden now - if (this._doNext === "hide") { - this._doNext = ""; - } - - // After hiding, send our "afterHide" event - this._sendEvent(_Overlay.afterHide); - this._writeProfilerMark("hide,StopTM"); // Overlay writes the stop profiler mark for all of its derived classes. - - - // If we had something queued, do that. This has to be after - // the afterHide event in case it triggers a show() and they - // have something to do in beforeShow that requires afterHide first. - Scheduler.schedule(this._checkDoNext, Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); - }, - - // Called after the animation but while the Overlay is still visible. It's - // important that this runs while the Overlay is visible because hiding - // a DOM element (e.g. visibility="hidden", display="none") while it contains - // focus has the side effect of moving focus to the body or null and triggering - // focus move events. _beforeEndHide is a good hook for the Overlay to move focus - // elsewhere before its DOM element gets hidden. - _beforeEndHide: function _Overlay_beforeEndHide() { - // Nothing by default - }, - - _checkDoNext: function _Overlay_checkDoNext() { - // Do nothing if we're still animating - if (this._animating || this._needToHandleHidingKeyboard || this._disposed) { - return; - } - - if (this._doNext === "hide") { - // Do hide first because animating commands would be easier - this._hide(); - this._doNext = ""; - } else if (this._queuedCommandAnimation) { - // Do queued commands before showing if possible - this._showAndHideQueue(); - } else if (this._doNext === "show") { - // Show last so that we don't unnecessarily animate commands - this._show(); - this._doNext = ""; - } - }, - - // Default animations - _baseAnimateIn: function _Overlay_baseAnimateIn() { - this._element.style.opacity = 0; - this._element.style.visibility = "visible"; - // touch opacity so that IE fades from the 0 we just set to 1 - _Global.getComputedStyle(this._element, null).opacity; - return Animations.fadeIn(this._element); - }, - - _baseAnimateOut: function _Overlay_baseAnimateOut() { - this._element.style.opacity = 1; - // touch opacity so that IE fades from the 1 we just set to 0 - _Global.getComputedStyle(this._element, null).opacity; - return Animations.fadeOut(this._element); - }, - - _animating: { - get: function _Overlay_animating_get() { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return !!this._element.winAnimating; - } - }, - - // Send one of our events - _sendEvent: function _Overlay_sendEvent(eventName, detail) { - if (this._disposed) { - return; - } - var event = _Global.document.createEvent("CustomEvent"); - event.initEvent(eventName, true, true, (detail || {})); - this._element.dispatchEvent(event); - }, - - // Show commands - _showCommands: function _Overlay_showCommands(commands, immediate) { - var showHide = this._resolveCommands(commands); - this._showAndHideCommands(showHide.commands, [], immediate); - }, - - // Hide commands - _hideCommands: function _Overlay_hideCommands(commands, immediate) { - var showHide = this._resolveCommands(commands); - this._showAndHideCommands([], showHide.commands, immediate); - }, - - // Hide commands - _showOnlyCommands: function _Overlay_showOnlyCommands(commands, immediate) { - var showHide = this._resolveCommands(commands); - this._showAndHideCommands(showHide.commands, showHide.others, immediate); - }, - - _showAndHideCommands: function _Overlay_showAndHideCommands(showCommands, hideCommands, immediate) { - // Immediate is "easy" - if (immediate || (this.hidden && !this._animating)) { - // Immediate mode (not animated) - this._showAndHideFast(showCommands, hideCommands); - // Need to remove them from queues, but others could be queued - this._removeFromQueue(showCommands, this._queuedToShow); - this._removeFromQueue(hideCommands, this._queuedToHide); - } else { - - // Queue Commands - this._updateAnimateQueue(showCommands, this._queuedToShow, this._queuedToHide); - this._updateAnimateQueue(hideCommands, this._queuedToHide, this._queuedToShow); - } - }, - - _removeFromQueue: function _Overlay_removeFromQueue(commands, queue) { - // remove commands from queue. - var count; - for (count = 0; count < commands.length; count++) { - // Remove if it was in queue - var countQ; - for (countQ = 0; countQ < queue.length; countQ++) { - if (queue[countQ] === commands[count]) { - queue.splice(countQ, 1); - break; - } - } - } - }, - - _updateAnimateQueue: function _Overlay_updateAnimateQueue(addCommands, toQueue, fromQueue) { - if (this._disposed) { - return; - } - - // Add addCommands to toQueue and remove addCommands from fromQueue. - var count; - for (count = 0; count < addCommands.length; count++) { - // See if it's already in toQueue - var countQ; - for (countQ = 0; countQ < toQueue.length; countQ++) { - if (toQueue[countQ] === addCommands[count]) { - break; - } - } - if (countQ === toQueue.length) { - // Not found, add it - toQueue[countQ] = addCommands[count]; - } - // Remove if it was in fromQueue - for (countQ = 0; countQ < fromQueue.length; countQ++) { - if (fromQueue[countQ] === addCommands[count]) { - fromQueue.splice(countQ, 1); - break; - } - } - } - // If we haven't queued the actual animation - if (!this._queuedCommandAnimation) { - // If not already animating, we'll need to call _checkDoNext - if (!this._animating) { - Scheduler.schedule(this._checkDoNext, Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); - } - this._queuedCommandAnimation = true; - } - }, - - // show/hide commands without doing any animation. - _showAndHideFast: function _Overlay_showAndHideFast(showCommands, hideCommands) { - var count; - var command; - for (count = 0; count < showCommands.length; count++) { - command = showCommands[count]; - if (command && command.style) { - command.style.visibility = ""; - command.style.display = ""; - } - } - for (count = 0; count < hideCommands.length; count++) { - command = hideCommands[count]; - if (command && command.style) { - command.style.visibility = "hidden"; - command.style.display = "none"; - } - } - - this._commandsUpdated(); - - }, - - // show and hide the queued commands, perhaps animating if overlay isn't hidden. - _showAndHideQueue: function _Overlay_showAndHideQueue() { - // Only called if not currently animating. - // We'll be done with the queued stuff when we return. - this._queuedCommandAnimation = false; - - // Shortcut if hidden - if (this.hidden) { - this._showAndHideFast(this._queuedToShow, this._queuedToHide); - // Might be something else to do - Scheduler.schedule(this._checkDoNext, Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); - } else { - // Animation has 3 parts: "hiding", "showing", and "moving" - // PVL has "addToList" and "deleteFromList", both of which allow moving parts. - // So we'll set up "add" for showing, and use "delete" for "hiding" + moving, - // then trigger both at the same time. - var showCommands = this._queuedToShow; - var hideCommands = this._queuedToHide; - var siblings = this._findSiblings(showCommands.concat(hideCommands)); - - // Filter out the commands queued for animation that don't need to be animated. - var count; - for (count = 0; count < showCommands.length; count++) { - // If this one's not real or not attached, skip it - if (!showCommands[count] || - !showCommands[count].style || - !_Global.document.body.contains(showCommands[count])) { - // Not real, skip it - showCommands.splice(count, 1); - count--; - } else if (showCommands[count].style.visibility !== "hidden" && showCommands[count].style.opacity !== "0") { - // Don't need to animate showing this one, already visible, so now it's a sibling - siblings.push(showCommands[count]); - showCommands.splice(count, 1); - count--; - } - } - for (count = 0; count < hideCommands.length; count++) { - // If this one's not real or not attached, skip it - if (!hideCommands[count] || - !hideCommands[count].style || - !_Global.document.body.contains(hideCommands[count]) || - hideCommands[count].style.visibility === "hidden" || - hideCommands[count].style.opacity === "0") { - // Don't need to animate hiding this one, not real, or it's hidden, - // so don't even need it as a sibling. - hideCommands.splice(count, 1); - count--; - } - } - - // Start command animations. - var commandsAnimationPromise = this._baseBeginAnimateCommands(showCommands, hideCommands, siblings); - - // Hook end animations - var that = this; - if (commandsAnimationPromise) { - // Needed to animate - commandsAnimationPromise.done( - function () { that._baseEndAnimateCommands(hideCommands); }, - function () { that._baseEndAnimateCommands(hideCommands); } - ); - } else { - // Already positioned correctly - Scheduler.schedule(function Overlay_async_baseEndAnimationCommands() { that._baseEndAnimateCommands([]); }, - Scheduler.Priority.normal, null, - "WinJS.UI._Overlay._endAnimateCommandsWithoutAnimation"); - } - } - - // Done, clear queues - this._queuedToShow = []; - this._queuedToHide = []; - }, - - _baseBeginAnimateCommands: function _Overlay_baseBeginAnimateCommands(showCommands, hideCommands, siblings) { - // The parameters are 3 mutually exclusive arrays of win-command elements contained in this Overlay. - // 1) showCommands[]: All of the HIDDEN win-command elements that ARE scheduled to show. - // 2) hideCommands[]: All of the VISIBLE win-command elements that ARE shceduled to hide. - // 3) siblings[]: i. All VISIBLE win-command elements that ARE NOT scheduled to hide. - // ii. All HIDDEN win-command elements that ARE NOT scheduled to hide OR show. - this._beginAnimateCommands(showCommands, hideCommands, this._getVisibleCommands(siblings)); - - var showAnimated = null, - hideAnimated = null; - - // Hide commands first, with siblings if necessary, - // so that the showing commands don't disrupt the hiding commands position. - if (hideCommands.length > 0) { - hideAnimated = Animations.createDeleteFromListAnimation(hideCommands, showCommands.length === 0 ? siblings : undefined); - } - if (showCommands.length > 0) { - showAnimated = Animations.createAddToListAnimation(showCommands, siblings); - } - - // Update hiding commands - for (var count = 0, len = hideCommands.length; count < len; count++) { - // Need to fix our position - var rectangle = hideCommands[count].getBoundingClientRect(), - style = _Global.getComputedStyle(hideCommands[count]); - - // Use the bounding box, adjusting for margins - hideCommands[count].style.top = (rectangle.top - parseFloat(style.marginTop)) + "px"; - hideCommands[count].style.left = (rectangle.left - parseFloat(style.marginLeft)) + "px"; - hideCommands[count].style.opacity = 0; - hideCommands[count].style.position = "fixed"; - } - - // Mark as animating - this._element.winAnimating = "rearranging"; - - // Start hiding animations - // Hide needs extra cleanup when done - var promise = null; - if (hideAnimated) { - promise = hideAnimated.execute(); - } - - // Update showing commands, - // After hiding commands so that the hiding ones fade in the right place. - for (count = 0; count < showCommands.length; count++) { - showCommands[count].style.visibility = ""; - showCommands[count].style.display = ""; - showCommands[count].style.opacity = 1; - } - - // Start showing animations - if (showAnimated) { - var newPromise = showAnimated.execute(); - if (promise) { - promise = Promise.join([promise, newPromise]); - } else { - promise = newPromise; - } - } - - return promise; - }, - - _beginAnimateCommands: function _Overlay_beginAnimateCommands() { - // Nothing by default - }, - - _getVisibleCommands: function _Overlay_getVisibleCommands(commandSubSet) { - var command, - commands = commandSubSet, - visibleCommands = []; - - if (!commands) { - // Crawl the inner HTML for the commands. - commands = this.element.querySelectorAll(".win-command"); - } - - for (var i = 0, len = commands.length; i < len; i++) { - command = commands[i].winControl || commands[i]; - if (!command.hidden) { - visibleCommands.push(command); - } - } - - return visibleCommands; - }, - - // Once animation is complete, ensure that the commands are display:none - // and check if there's another animation to start. - _baseEndAnimateCommands: function _Overlay_baseEndAnimateCommands(hideCommands) { - if (this._disposed) { - return; - } - - // Update us - var count; - for (count = 0; count < hideCommands.length; count++) { - // Force us back into our appbar so that we can show again correctly - hideCommands[count].style.position = ""; - hideCommands[count].style.top = ""; - hideCommands[count].style.left = ""; - hideCommands[count].getBoundingClientRect(); - // Now make us really hidden - hideCommands[count].style.visibility = "hidden"; - hideCommands[count].style.display = "none"; - hideCommands[count].style.opacity = 1; - } - // Done animating - this._element.winAnimating = ""; - - this._endAnimateCommands(); - - // Might be something else to do - this._checkDoNext(); - }, - - _endAnimateCommands: function _Overlay_endAnimateCommands() { - // Nothing by default - }, - - // Resolves our commands - _resolveCommands: function _Overlay_resolveCommands(commands) { - // First make sure they're all DOM elements. - commands = _resolveElements(commands); - - // Now make sure they're all in this container - var result = {}; - result.commands = []; - result.others = []; - var allCommands = this.element.querySelectorAll(".win-command"); - var countAll, countIn; - for (countAll = 0; countAll < allCommands.length; countAll++) { - var found = false; - for (countIn = 0; countIn < commands.length; countIn++) { - if (commands[countIn] === allCommands[countAll]) { - result.commands.push(allCommands[countAll]); - commands.splice(countIn, 1); - found = true; - break; - } - } - if (!found) { - result.others.push(allCommands[countAll]); - } - } - return result; - }, - - // Find siblings, all DOM elements now. - // Returns all .win-commands in this Overlay that are NOT in the passed in 'commands' array. - _findSiblings: function _Overlay_findSiblings(commands) { - // Now make sure they're all in this container - var siblings = []; - var allCommands = this.element.querySelectorAll(".win-command"); - var countAll, countIn; - for (countAll = 0; countAll < allCommands.length; countAll++) { - var found = false; - for (countIn = 0; countIn < commands.length; countIn++) { - if (commands[countIn] === allCommands[countAll]) { - commands.splice(countIn, 1); - found = true; - break; - } - } - if (!found) { - siblings.push(allCommands[countAll]); - } - } - return siblings; - }, - - _baseResize: function _Overlay_baseResize(event) { - // Call specific resize - this._resize(event); - }, - - _hideOrDismiss: function _Overlay_hideOrDismiss() { - var element = this._element; - if (element && _ElementUtilities.hasClass(element, _Constants.settingsFlyoutClass)) { - this._dismiss(); - } else if (element && _ElementUtilities.hasClass(element, _Constants.appBarClass)) { - this.close(); - } else { - this.hide(); - } - }, - - _resize: function _Overlay_resize() { - // Nothing by default - }, - - _commandsUpdated: function _Overlay_commandsUpdated() { - // Nothing by default - }, - - _checkScrollPosition: function _Overlay_checkScrollPosition() { - // Nothing by default - }, - - _showingKeyboard: function _Overlay_showingKeyboard() { - // Nothing by default - }, - - _hidingKeyboard: function _Overlay_hidingKeyboard() { - // Nothing by default - }, - - // Verify that this HTML AppBar only has AppBar/MenuCommands. - _verifyCommandsOnly: function _Overlay_verifyCommandsOnly(element, type) { - var children = element.children; - var commands = new Array(children.length); - for (var i = 0; i < children.length; i++) { - // If constructed they have win-command class, otherwise they have data-win-control - if (!_ElementUtilities.hasClass(children[i], "win-command") && - children[i].getAttribute("data-win-control") !== type) { - // Wasn't tagged with class or AppBar/MenuCommand, not an AppBar/MenuCommand - throw new _ErrorFromName("WinJS.UI._Overlay.MustContainCommands", strings.mustContainCommands); - } else { - // Instantiate the commands. - ControlProcessor.processAll(children[i]); - commands[i] = children[i].winControl; - } - } - return commands; - }, - - // Sets focus on what we think is the last tab stop. If nothing is focusable will - // try to set focus on itself. - _focusOnLastFocusableElementOrThis: function _Overlay_focusOnLastFocusableElementOrThis() { - if (!this._focusOnLastFocusableElement()) { - // Nothing is focusable. Set focus to this. - _Overlay._trySetActive(this._element); - } - }, - - // Sets focus to what we think is the last tab stop. This element must have - // a firstDiv with tabIndex equal to the lowest tabIndex in the element - // and a finalDiv with tabIndex equal to the highest tabIndex in the element. - // Also the firstDiv must be its first child and finalDiv be its last child. - // Returns true if successful, false otherwise. - _focusOnLastFocusableElement: function _Overlay_focusOnLastFocusableElement() { - if (this._element.firstElementChild) { - var oldFirstTabIndex = this._element.firstElementChild.tabIndex; - var oldLastTabIndex = this._element.lastElementChild.tabIndex; - this._element.firstElementChild.tabIndex = -1; - this._element.lastElementChild.tabIndex = -1; - - var tabResult = _ElementUtilities._focusLastFocusableElement(this._element); - - if (tabResult) { - _Overlay._trySelect(_Global.document.activeElement); - } - - this._element.firstElementChild.tabIndex = oldFirstTabIndex; - this._element.lastElementChild.tabIndex = oldLastTabIndex; - - return tabResult; - } else { - return false; - } - }, - - - // Sets focus on what we think is the first tab stop. If nothing is focusable will - // try to set focus on itself. - _focusOnFirstFocusableElementOrThis: function _Overlay_focusOnFirstFocusableElementOrThis() { - if (!this._focusOnFirstFocusableElement()) { - // Nothing is focusable. Set focus to this. - _Overlay._trySetActive(this._element); - } - }, - - // Sets focus to what we think is the first tab stop. This element must have - // a firstDiv with tabIndex equal to the lowest tabIndex in the element - // and a finalDiv with tabIndex equal to the highest tabIndex in the element. - // Also the firstDiv must be its first child and finalDiv be its last child. - // Returns true if successful, false otherwise. - _focusOnFirstFocusableElement: function _Overlay__focusOnFirstFocusableElement(useSetActive, scroller) { - if (this._element.firstElementChild) { - var oldFirstTabIndex = this._element.firstElementChild.tabIndex; - var oldLastTabIndex = this._element.lastElementChild.tabIndex; - this._element.firstElementChild.tabIndex = -1; - this._element.lastElementChild.tabIndex = -1; - - var tabResult = _ElementUtilities._focusFirstFocusableElement(this._element, useSetActive, scroller); - - if (tabResult) { - _Overlay._trySelect(_Global.document.activeElement); - } - - this._element.firstElementChild.tabIndex = oldFirstTabIndex; - this._element.lastElementChild.tabIndex = oldLastTabIndex; - - return tabResult; - } else { - return false; - } - }, - - _writeProfilerMark: function _Overlay_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI._Overlay:" + this._id + ":" + text); - } - }, - { - // Statics - - _isFlyoutVisible: function () { - var flyouts = _Global.document.querySelectorAll("." + _Constants.flyoutClass); - for (var i = 0; i < flyouts.length; i++) { - var flyoutControl = flyouts[i].winControl; - if (flyoutControl && !flyoutControl.hidden) { - return true; - } - } - - return false; - }, - - // Try to set us as active - _trySetActive: function (element, scroller) { - if (!element || !_Global.document.body || !_Global.document.body.contains(element)) { - return false; - } - if (!_ElementUtilities._setActive(element, scroller)) { - return false; - } - return (element === _Global.document.activeElement); - }, - - // Try to select the text so keyboard can be used. - _trySelect: function (element) { - try { - if (element && element.select) { - element.select(); - } - } catch (e) { } - }, - - _sizeOfDocument: function () { - return { - width: _Global.document.documentElement.offsetWidth, - height: _Global.document.documentElement.offsetHeight, - }; - }, - - _getParentControlUsingClassName: function (element, className) { - while (element && element !== _Global.document.body) { - if (_ElementUtilities.hasClass(element, className)) { - return element.winControl; - } - element = element.parentNode; - } - return null; - }, - - // Static controller for _Overlay global events registering/unregistering. - _globalEventListeners: new _GlobalListener(), - - // Show/Hide all bars - _hideAppBars: function _Overlay_hideAppBars(bars, keyboardInvoked) { - var allBarsAnimationPromises = bars.map(function (bar) { - bar.close(); - return bar._animationPromise; - }); - return Promise.join(allBarsAnimationPromises); - }, - - _showAppBars: function _Overlay_showAppBars(bars, keyboardInvoked) { - var allBarsAnimationPromises = bars.map(function (bar) { - bar._show(); - return bar._animationPromise; - }); - return Promise.join(allBarsAnimationPromises); - }, - - // WWA Soft Keyboard offsets - _keyboardInfo: _KeyboardInfo._KeyboardInfo, - - // Padding for IHM timer to allow for first scroll event - _scrollTimeout: _KeyboardInfo._KeyboardInfo._scrollTimeout, - - // Events - beforeShow: "beforeshow", - beforeHide: "beforehide", - afterShow: "aftershow", - afterHide: "afterhide", - - commonstrings: { - get cannotChangeCommandsWhenVisible() { return "Invalid argument: You must call hide() before changing {0} commands"; }, - get cannotChangeHiddenProperty() { return "Unable to set hidden property while parent {0} is visible."; } - }, - }); - - _Base.Class.mix(_Overlay, _Control.DOMEventMixin); - - return _Overlay; - }) - }); - -}); - - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// appbar,Flyout,Flyouts,Statics -define('WinJS/Controls/Flyout',[ - 'exports', - '../Core/_Global', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_ErrorFromName', - '../Core/_Events', - '../Core/_Log', - '../Core/_Resources', - '../Core/_WriteProfilerMark', - '../Animations', - '../_Signal', - '../_LightDismissService', - '../Utilities/_Dispose', - '../Utilities/_ElementUtilities', - '../Utilities/_KeyboardBehavior', - '../Utilities/_Hoverable', - './_LegacyAppBar/_Constants', - './Flyout/_Overlay' -], function flyoutInit(exports, _Global, _Base, _BaseUtils, _ErrorFromName, _Events, _Log, _Resources, _WriteProfilerMark, Animations, _Signal, _LightDismissService, _Dispose, _ElementUtilities, _KeyboardBehavior, _Hoverable, _Constants, _Overlay) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// - /// Displays lightweight UI that is either informational, or requires user interaction. - /// Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. - /// - /// - /// - /// Flyout - /// - /// - /// ]]> - /// Raised just before showing a flyout. - /// Raised immediately after a flyout is fully shown. - /// Raised just before hiding a flyout. - /// Raised immediately after a flyout is fully hidden. - /// The Flyout control itself. - /// - /// - Flyout: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - function getDimension(element, property) { - return _ElementUtilities.convertToPixels(element, _Global.getComputedStyle(element, null)[property]); - } - - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/flyoutAriaLabel").value; }, - get noAnchor() { return "Invalid argument: Flyout anchor element not found in DOM."; }, - get badPlacement() { return "Invalid argument: Flyout placement should be 'top' (default), 'bottom', 'left', 'right', 'auto', 'autohorizontal', or 'autovertical'."; }, - get badAlignment() { return "Invalid argument: Flyout alignment should be 'center' (default), 'left', or 'right'."; } - }; - - var createEvent = _Events._createEventProperty; - - // _LightDismissableLayer is an ILightDismissable which manages a set of ILightDismissables. - // It acts as a proxy between the LightDismissService and the light dismissables it manages. - // It enables multiple dismissables to be above the click eater at the same time. - var _LightDismissableLayer = _Base.Class.define(function _LightDismissableLayer_ctor(onLightDismiss) { - this._onLightDismiss = onLightDismiss; - this._currentlyFocusedClient = null; - this._clients = []; // Array of ILightDismissables - }, { - // Dismissables should call this as soon as they are ready to be shown. More specifically, they should call this: - // - After they are in the DOM and ready to receive focus (e.g. style.display cannot be "none") - // - Before their entrance animation is played - shown: function _LightDismissableLayer_shown(client /*: ILightDismissable */) { - client._focusable = true; - var index = this._clients.indexOf(client); - if (index === -1) { - this._clients.push(client); - client.onShow(this); - if (!_LightDismissService.isShown(this)) { - _LightDismissService.shown(this); - } else { - _LightDismissService.updated(this); - this._activateTopFocusableClientIfNeeded(); - } - } - }, - - // Dismissables should call this at the start of their exit animation. A "hiding", - // dismissable will still be rendered with the proper z-index but it will no - // longer be given focus. Also, focus is synchronously moved out of this dismissable. - hiding: function _LightDismissableLayer_hiding(client /*: ILightDismissable */) { - var index = this._clients.indexOf(client); - if (index !== -1) { - this._clients[index]._focusable = false; - this._activateTopFocusableClientIfNeeded(); - } - }, - - // Dismissables should call this when they are done being dismissed (i.e. after their exit animation has finished) - hidden: function _LightDismissableLayer_hidden(client /*: ILightDismissable */) { - var index = this._clients.indexOf(client); - if (index !== -1) { - this._clients.splice(index, 1); - client.setZIndex(""); - client.onHide(); - if (this._clients.length === 0) { - _LightDismissService.hidden(this); - } else { - _LightDismissService.updated(this); - this._activateTopFocusableClientIfNeeded(); - } - } - }, - - keyDown: function _LightDismissableLayer_keyDown(client /*: ILightDismissable */, eventObject) { - _LightDismissService.keyDown(this, eventObject); - }, - keyUp: function _LightDismissableLayer_keyUp(client /*: ILightDismissable */, eventObject) { - _LightDismissService.keyUp(this, eventObject); - }, - keyPress: function _LightDismissableLayer_keyPress(client /*: ILightDismissable */, eventObject) { - _LightDismissService.keyPress(this, eventObject); - }, - - // Used by tests. - clients: { - get: function _LightDismissableLayer_clients_get() { - return this._clients; - } - }, - - _clientForElement: function _LightDismissableLayer_clientForElement(element) { - for (var i = this._clients.length - 1; i >= 0; i--) { - if (this._clients[i].containsElement(element)) { - return this._clients[i]; - } - } - return null; - }, - - _focusableClientForElement: function _LightDismissableLayer_focusableClientForElement(element) { - for (var i = this._clients.length - 1; i >= 0; i--) { - if (this._clients[i]._focusable && this._clients[i].containsElement(element)) { - return this._clients[i]; - } - } - return null; - }, - - _getTopmostFocusableClient: function _LightDismissableLayer_getTopmostFocusableClient() { - for (var i = this._clients.length - 1; i >= 0; i--) { - var client = this._clients[i]; - if (client && client._focusable) { - return client; - } - } - return null; - }, - - _activateTopFocusableClientIfNeeded: function _LightDismissableLayer_activateTopFocusableClientIfNeeded() { - var topClient = this._getTopmostFocusableClient(); - if (topClient && _LightDismissService.isTopmost(this)) { - // If the last input type was keyboard, use focus() so a keyboard focus visual is drawn. - // Otherwise, use setActive() so no focus visual is drawn. - var useSetActive = !_KeyboardBehavior._keyboardSeenLast; - topClient.onTakeFocus(useSetActive); - } - }, - - // ILightDismissable - // - - setZIndex: function _LightDismissableLayer_setZIndex(zIndex) { - this._clients.forEach(function (client, index) { - client.setZIndex(zIndex + index); - }, this); - }, - getZIndexCount: function _LightDismissableLayer_getZIndexCount() { - return this._clients.length; - }, - containsElement: function _LightDismissableLayer_containsElement(element) { - return !!this._clientForElement(element); - }, - onTakeFocus: function _LightDismissableLayer_onTakeFocus(useSetActive) { - // Prefer the client that has focus - var client = this._focusableClientForElement(_Global.document.activeElement); - - if (!client && this._clients.indexOf(this._currentlyFocusedClient) !== -1 && this._currentlyFocusedClient._focusable) { - // Next try the client that had focus most recently - client = this._currentlyFocusedClient; - } - - if (!client) { - // Finally try the client at the top of the stack - client = this._getTopmostFocusableClient(); - } - - this._currentlyFocusedClient = client; - client && client.onTakeFocus(useSetActive); - }, - onFocus: function _LightDismissableLayer_onFocus(element) { - this._currentlyFocusedClient = this._clientForElement(element); - this._currentlyFocusedClient && this._currentlyFocusedClient.onFocus(element); - }, - onShow: function _LightDismissableLayer_onShow(service /*: ILightDismissService */) { }, - onHide: function _LightDismissableLayer_onHide() { - this._currentlyFocusedClient = null; - }, - onKeyInStack: function _LightDismissableLayer_onKeyInStack(info /*: IKeyboardInfo*/) { - // A keyboard event occurred in the light dismiss stack. Notify the flyouts to - // give them the opportunity to handle this evnet. - var index = this._clients.indexOf(this._currentlyFocusedClient); - if (index !== -1) { - var clients = this._clients.slice(0, index + 1); - for (var i = clients.length - 1; i >= 0 && !info.propagationStopped; i--) { - if (clients[i]._focusable) { - clients[i].onKeyInStack(info); - } - } - } - }, - onShouldLightDismiss: function _LightDismissableLayer_onShouldLightDismiss(info) { - return _LightDismissService.DismissalPolicies.light(info); - }, - onLightDismiss: function _LightDismissableLayer_onLightDismiss(info) { - this._onLightDismiss(info); - } - }); - - // Singleton class for managing cascading flyouts - var _CascadeManager = _Base.Class.define(function _CascadeManager_ctor() { - var that = this; - this._dismissableLayer = new _LightDismissableLayer(function _CascadeManager_onLightDismiss(info) { - if (info.reason === _LightDismissService.LightDismissalReasons.escape) { - that.collapseFlyout(that.getAt(that.length - 1)); - } else { - that.collapseAll(); - } - }); - this._cascadingStack = []; - this._handleKeyDownInCascade_bound = this._handleKeyDownInCascade.bind(this); - this._inputType = null; - }, - { - appendFlyout: function _CascadeManager_appendFlyout(flyoutToAdd) { - // PRECONDITION: flyoutToAdd must not already be in the cascade. - _Log.log && this.indexOf(flyoutToAdd) >= 0 && _Log.log('_CascadeManager is attempting to append a Flyout that is already in the cascade.', "winjs _CascadeManager", "error"); - // PRECONDITION: this.reentrancyLock must be false. appendFlyout should only be called from baseFlyoutShow() which is the function responsible for preventing reentrancy. - _Log.log && this.reentrancyLock && _Log.log('_CascadeManager is attempting to append a Flyout through reentrancy.', "winjs _CascadeManager", "error"); - - // IF the anchor element for flyoutToAdd is contained within another flyout, - // && that flyout is currently in the cascadingStack, consider that flyout to be the parent of flyoutToAdd: - // Remove from the cascadingStack, any subflyout descendants of the parent flyout. - // ELSE flyoutToAdd isn't anchored to any of the Flyouts in the existing cascade - // Collapse the entire cascadingStack to start a new cascade. - // FINALLY: - // add flyoutToAdd to the end of the cascading stack. Monitor it for events. - var indexOfParentFlyout = this.indexOfElement(flyoutToAdd._currentAnchor); - if (indexOfParentFlyout >= 0) { - this.collapseFlyout(this.getAt(indexOfParentFlyout + 1)); - } else { - this.collapseAll(); - } - - flyoutToAdd.element.addEventListener("keydown", this._handleKeyDownInCascade_bound, false); - this._cascadingStack.push(flyoutToAdd); - this._dismissableLayer.shown(flyoutToAdd._dismissable); - }, - collapseFlyout: function _CascadeManager_collapseFlyout(flyout) { - // Removes flyout param and its subflyout descendants from the _cascadingStack. - if (!this.reentrancyLock && flyout && this.indexOf(flyout) >= 0) { - this.reentrancyLock = true; - var signal = new _Signal(); - this.unlocked = signal.promise; - - var subFlyout; - while (this.length && flyout !== subFlyout) { - subFlyout = this._cascadingStack.pop(); - subFlyout.element.removeEventListener("keydown", this._handleKeyDownInCascade_bound, false); - subFlyout._hide(); // We use the reentrancyLock to prevent reentrancy here. - } - - if (this._cascadingStack.length === 0) { - // The cascade is empty so clear the input type. This gives us the opportunity - // to recalculate the input type when the next cascade starts. - this._inputType = null; - } - - this.reentrancyLock = false; - this.unlocked = null; - signal.complete(); - } - }, - flyoutHiding: function _CascadeManager_flyoutHiding(flyout) { - this._dismissableLayer.hiding(flyout._dismissable); - }, - flyoutHidden: function _CascadeManager_flyoutHidden(flyout) { - this._dismissableLayer.hidden(flyout._dismissable); - }, - collapseAll: function _CascadeManager_collapseAll() { - // Empties the _cascadingStack and hides all flyouts. - var headFlyout = this.getAt(0); - if (headFlyout) { - this.collapseFlyout(headFlyout); - } - }, - indexOf: function _CascadeManager_indexOf(flyout) { - return this._cascadingStack.indexOf(flyout); - }, - indexOfElement: function _CascadeManager_indexOfElement(el) { - // Returns an index cooresponding to the Flyout in the cascade whose element contains the element in question. - // Returns -1 if the element is not contained by any Flyouts in the cascade. - var indexOfAssociatedFlyout = -1; - for (var i = 0, len = this.length; i < len; i++) { - var currentFlyout = this.getAt(i); - if (currentFlyout.element.contains(el)) { - indexOfAssociatedFlyout = i; - break; - } - } - return indexOfAssociatedFlyout; - }, - length: { - get: function _CascadeManager_getLength() { - return this._cascadingStack.length; - } - }, - getAt: function _CascadeManager_getAt(index) { - return this._cascadingStack[index]; - }, - handleFocusIntoFlyout: function _CascadeManager_handleFocusIntoFlyout(event) { - // When a flyout in the cascade recieves focus, we close all subflyouts beneath it. - var index = this.indexOfElement(event.target); - if (index >= 0) { - var subFlyout = this.getAt(index + 1); - this.collapseFlyout(subFlyout); - } - }, - // Compute the input type that is associated with the cascading stack on demand. Allows - // each Flyout in the cascade to adjust its sizing based on the current input type - // and to do it in a way that is consistent with the rest of the Flyouts in the cascade. - inputType: { - get: function _CascadeManager_inputType_get() { - if (!this._inputType) { - this._inputType = _KeyboardBehavior._lastInputType; - } - return this._inputType; - } - }, - // Used by tests. - dismissableLayer: { - get: function _CascadeManager_dismissableLayer_get() { - return this._dismissableLayer; - } - }, - _handleKeyDownInCascade: function _CascadeManager_handleKeyDownInCascade(event) { - var rtl = _Global.getComputedStyle(event.target).direction === "rtl", - leftKey = rtl ? Key.rightArrow : Key.leftArrow, - target = event.target; - - if (event.keyCode === leftKey) { - // Left key press in a SubFlyout will close that subFlyout and any subFlyouts cascading from it. - var index = this.indexOfElement(target); - if (index >= 1) { - var subFlyout = this.getAt(index); - this.collapseFlyout(subFlyout); - // Prevent document scrolling - event.preventDefault(); - } - } else if (event.keyCode === Key.alt || event.keyCode === Key.F10) { - this.collapseAll(); - } - } - }); - - var AnimationOffsets = { - top: { top: "50px", left: "0px", keyframe: "WinJS-showFlyoutTop" }, - bottom: { top: "-50px", left: "0px", keyframe: "WinJS-showFlyoutBottom" }, - left: { top: "0px", left: "50px", keyframe: "WinJS-showFlyoutLeft" }, - right: { top: "0px", left: "-50px", keyframe: "WinJS-showFlyoutRight" }, - }; - - var Flyout = _Base.Class.derive(_Overlay._Overlay, function Flyout_ctor(element, options) { - /// - /// - /// Creates a new Flyout control. - /// - /// - /// The DOM element that hosts the control. - /// - /// - /// The set of properties and values to apply to the new Flyout. - /// - /// The new Flyout control. - /// - /// - - // Simplify checking later - options = options || {}; - - // Make sure there's an input element - this._element = element || _Global.document.createElement("div"); - this._id = this._element.id || _ElementUtilities._uniqueID(this._element); - this._writeProfilerMark("constructor,StartTM"); - - this._baseFlyoutConstructor(this._element, options); - - var _elms = this._element.getElementsByTagName("*"); - var firstDiv = this._addFirstDiv(); - firstDiv.tabIndex = _ElementUtilities._getLowestTabIndexInList(_elms); - var finalDiv = this._addFinalDiv(); - finalDiv.tabIndex = _ElementUtilities._getHighestTabIndexInList(_elms); - - // Handle "esc" & "tab" key presses - this._element.addEventListener("keydown", this._handleKeyDown, true); - - this._writeProfilerMark("constructor,StopTM"); - return this; - }, { - _lastMaxHeight: null, - - _baseFlyoutConstructor: function Flyout_baseFlyoutContstructor(element, options) { - // Flyout constructor - - // We have some options with defaults - this._placement = "auto"; - this._alignment = "center"; - - // Call the base overlay constructor helper - this._baseOverlayConstructor(element, options); - - // Start flyouts hidden - this._element.style.visibilty = "hidden"; - this._element.style.display = "none"; - - // Attach our css class - _ElementUtilities.addClass(this._element, _Constants.flyoutClass); - - var that = this; - // Each flyout has an ILightDismissable that is managed through the - // CascasdeManager rather than by the _LightDismissService directly. - this._dismissable = new _LightDismissService.LightDismissableElement({ - element: this._element, - tabIndex: this._element.hasAttribute("tabIndex") ? this._element.tabIndex : -1, - onLightDismiss: function () { - that.hide(); - }, - onTakeFocus: function (useSetActive) { - if (!that._dismissable.restoreFocus()) { - if (!_ElementUtilities.hasClass(that.element, _Constants.menuClass)) { - // Put focus on the first child in the Flyout - that._focusOnFirstFocusableElementOrThis(); - } else { - // Make sure the menu has focus, but don't show a focus rect - _Overlay._Overlay._trySetActive(that._element); - } - } - } - }); - - // Make sure we have an ARIA role - var role = this._element.getAttribute("role"); - if (role === null || role === "" || role === undefined) { - if (_ElementUtilities.hasClass(this._element, _Constants.menuClass)) { - this._element.setAttribute("role", "menu"); - } else { - this._element.setAttribute("role", "dialog"); - } - } - var label = this._element.getAttribute("aria-label"); - if (label === null || label === "" || label === undefined) { - this._element.setAttribute("aria-label", strings.ariaLabel); - } - - // Base animation is popIn, but our flyout has different arguments - this._currentAnimateIn = this._flyoutAnimateIn; - this._currentAnimateOut = this._flyoutAnimateOut; - - _ElementUtilities._addEventListener(this.element, "focusin", this._handleFocusIn.bind(this), false); - }, - - /// - /// Gets or sets the Flyout control's anchor. The anchor element is the HTML element which the Flyout originates from and is positioned relative to. - /// (This setting can be overridden when you call the show method.) - /// - /// - anchor: { - get: function () { - return this._anchor; - }, - set: function (value) { - this._anchor = value; - } - }, - - /// - /// Gets or sets the default placement of this Flyout. (This setting can be overridden when you call the show method.) - /// - /// - placement: { - get: function () { - return this._placement; - }, - set: function (value) { - if (value !== "top" && value !== "bottom" && value !== "left" && value !== "right" && value !== "auto" && value !== "autohorizontal" && value !== "autovertical") { - // Not a legal placement value - throw new _ErrorFromName("WinJS.UI.Flyout.BadPlacement", strings.badPlacement); - } - this._placement = value; - } - }, - - /// - /// Gets or sets the default alignment for this Flyout. (This setting can be overridden when you call the show method.) - /// - /// - alignment: { - get: function () { - return this._alignment; - }, - set: function (value) { - if (value !== "right" && value !== "left" && value !== "center") { - // Not a legal alignment value - throw new _ErrorFromName("WinJS.UI.Flyout.BadAlignment", strings.badAlignment); - } - this._alignment = value; - } - }, - - /// Disable a Flyout, setting or getting the HTML disabled attribute. When disabled the Flyout will no longer display with show(), and will hide if currently visible. - disabled: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return !!this._element.disabled; - }, - set: function (value) { - // Force this check into a boolean because our current state could be a bit confused since we tie to the DOM element - value = !!value; - var oldValue = !!this._element.disabled; - if (oldValue !== value) { - this._element.disabled = value; - if (!this.hidden && this._element.disabled) { - this.hide(); - } - } - } - }, - - /// - /// Occurs immediately before the control is shown. - /// - onbeforeshow: createEvent(_Overlay._Overlay.beforeShow), - - /// - /// Occurs immediately after the control is shown. - /// - onaftershow: createEvent(_Overlay._Overlay.afterShow), - - /// - /// Occurs immediately before the control is hidden. - /// - onbeforehide: createEvent(_Overlay._Overlay.beforeHide), - - /// - /// Occurs immediately after the control is hidden. - /// - onafterhide: createEvent(_Overlay._Overlay.afterHide), - - _dispose: function Flyout_dispose() { - _Dispose.disposeSubTree(this.element); - this._hide(); - Flyout._cascadeManager.flyoutHidden(this); - this.anchor = null; - }, - - show: function (anchor, placement, alignment) { - /// - /// - /// Shows the Flyout, if hidden, regardless of other states. - /// - /// - /// The DOM element, or ID of a DOM element to anchor the Flyout, overriding the anchor property for this time only. - /// - /// - /// The placement of the Flyout to the anchor: 'auto' (default), 'top', 'bottom', 'left', or 'right'. This parameter overrides the placement property for this show only. - /// - /// - /// For 'top' or 'bottom' placement, the alignment of the Flyout to the anchor's edge: 'center' (default), 'left', or 'right'. - /// This parameter overrides the alignment property for this show only. - /// - /// - /// - this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). - this._show(anchor, placement, alignment); - }, - - _show: function Flyout_show(anchor, placement, alignment) { - this._baseFlyoutShow(anchor, placement, alignment); - }, - - hide: function () { - /// - /// - /// Hides the Flyout, if visible, regardless of other states. - /// - /// - /// - // Just wrap the private one, turning off keyboard invoked flag - this._writeProfilerMark("hide,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndHide(). - this._hide(); - }, - - _hide: function Flyout_hide() { - - // First close all subflyout descendants in the cascade. - // Any calls to collapseFlyout through reentrancy should nop. - Flyout._cascadeManager.collapseFlyout(this); - - if (this._baseHide()) { - Flyout._cascadeManager.flyoutHiding(this); - } - }, - - _beforeEndHide: function Flyout_beforeEndHide() { - Flyout._cascadeManager.flyoutHidden(this); - }, - - _baseFlyoutShow: function Flyout_baseFlyoutShow(anchor, placement, alignment) { - if (this.disabled || this._disposed) { - // Don't do anything. - return; - } - - // Pick up defaults - if (!anchor) { - anchor = this._anchor; - } - if (!placement) { - placement = this._placement; - } - if (!alignment) { - alignment = this._alignment; - } - - // Dereference the anchor if necessary - if (typeof anchor === "string") { - anchor = _Global.document.getElementById(anchor); - } else if (anchor && anchor.element) { - anchor = anchor.element; - } - - // We expect an anchor - if (!anchor) { - // If we have _nextLeft, etc., then we were continuing an old animation, so that's OK - if (!this._reuseCurrent) { - throw new _ErrorFromName("WinJS.UI.Flyout.NoAnchor", strings.noAnchor); - } - // Last call was incomplete, so reuse the previous _current values. - this._reuseCurrent = null; - } else { - // Remember the anchor so that if we lose focus we can go back - this._currentAnchor = anchor; - // Remember current values - this._currentPlacement = placement; - this._currentAlignment = alignment; - } - - // If we're animating (eg baseShow is going to fail), or the cascadeManager is in the middle of a updating the cascade, - // then don't mess up our current state. - if (this._element.winAnimating) { - this._reuseCurrent = true; - // Queue us up to wait for the current animation to finish. - // _checkDoNext() is always scheduled after the current animation completes. - this._doNext = "show"; - } else if (Flyout._cascadeManager.reentrancyLock) { - this._reuseCurrent = true; - // Queue us up to wait for the current animation to finish. - // Schedule a call to _checkDoNext() for when the cascadeManager unlocks. - this._doNext = "show"; - var that = this; - Flyout._cascadeManager.unlocked.then(function () { that._checkDoNext(); }); - } else { - // We call our base _baseShow to handle the actual animation - if (this._baseShow()) { - // (_baseShow shouldn't ever fail because we tested winAnimating above). - if (!_ElementUtilities.hasClass(this.element, "win-menu")) { - // Verify that the firstDiv is in the correct location. - // Move it to the correct location or add it if not. - var _elms = this._element.getElementsByTagName("*"); - var firstDiv = this.element.querySelectorAll(".win-first"); - if (this.element.children.length && !_ElementUtilities.hasClass(this.element.children[0], _Constants.firstDivClass)) { - if (firstDiv && firstDiv.length > 0) { - firstDiv.item(0).parentNode.removeChild(firstDiv.item(0)); - } - - firstDiv = this._addFirstDiv(); - } - firstDiv.tabIndex = _ElementUtilities._getLowestTabIndexInList(_elms); - - // Verify that the finalDiv is in the correct location. - // Move it to the correct location or add it if not. - var finalDiv = this.element.querySelectorAll(".win-final"); - if (!_ElementUtilities.hasClass(this.element.children[this.element.children.length - 1], _Constants.finalDivClass)) { - if (finalDiv && finalDiv.length > 0) { - finalDiv.item(0).parentNode.removeChild(finalDiv.item(0)); - } - - finalDiv = this._addFinalDiv(); - } - finalDiv.tabIndex = _ElementUtilities._getHighestTabIndexInList(_elms); - } - - Flyout._cascadeManager.appendFlyout(this); - } - } - }, - - _lightDismiss: function Flyout_lightDismiss() { - Flyout._cascadeManager.collapseAll(); - }, - - // Find our new flyout position. - _findPosition: function Flyout_findPosition() { - this._adjustedHeight = 0; - this._nextTop = 0; - this._nextLeft = 0; - this._keyboardMovedUs = false; - this._doesScroll = false; - - // Make sure menu commands display correctly - if (this._checkMenuCommands) { - this._checkMenuCommands(); - } - - // Remove old height restrictions and scrolling. - this._clearAdjustedStyles(); - - this._setAlignment(this._currentAlignment); - - // Set up the new position, and prep the offset for showPopup. - this._getTopLeft(); - - // Adjust position - if (this._nextTop < 0) { - // Overran bottom, attach to bottom. - this._element.style.bottom = _Overlay._Overlay._keyboardInfo._visibleDocBottomOffset + "px"; - this._element.style.top = "auto"; - } else { - // Normal, set top - this._element.style.top = this._nextTop + "px"; - this._element.style.bottom = "auto"; - } - if (this._nextLeft < 0) { - // Overran right, attach to right - this._element.style.right = "0px"; - this._element.style.left = "auto"; - } else { - // Normal, set left - this._element.style.left = this._nextLeft + "px"; - this._element.style.right = "auto"; - } - - // Adjust height/scrollbar - if (this._doesScroll) { - _ElementUtilities.addClass(this._element, _Constants.scrollsClass); - this._lastMaxHeight = this._element.style.maxHeight; - this._element.style.maxHeight = this._adjustedHeight + "px"; - } - - // May need to adjust if the IHM is showing. - if (_Overlay._Overlay._keyboardInfo._visible) { - // Use keyboard logic - this._checkKeyboardFit(); - - if (this._keyboardMovedUs) { - this._adjustForKeyboard(); - } - } - }, - - // This determines our positioning. We have 8 modes, the 1st four are explicit, the last 4 are automatic: - // * top - position explicitly on the top of the anchor, shrinking and adding scrollbar as needed. - // * bottom - position explicitly below the anchor, shrinking and adding scrollbar as needed. - // * left - position left of the anchor, shrinking and adding a vertical scrollbar as needed. - // * right - position right of the anchor, shrinking and adding a vertical scroolbar as needed. - // * auto - Automatic placement. - // * autohorizontal - Automatic placement (only left or right). - // * autovertical - Automatic placement (only top or bottom). - // * _cascasde - Private placement used by MenuCommand._activateFlyoutCommand - // Auto tests the height of the anchor and the flyout. For consistency in orientation, we imagine - // that the anchor is placed in the vertical center of the display. If the flyout would fit above - // that centered anchor, then we will place the flyout vertically in relation to the anchor, otherwise - // placement will be horizontal. - // Vertical auto or autovertical placement will be positioned on top of the anchor if room, otherwise below the anchor. - // - this is because touch users would be more likely to obscure flyouts below the anchor. - // Horizontal auto or autohorizontal placement will be positioned to the left of the anchor if room, otherwise to the right. - // - this is because right handed users would be more likely to obscure a flyout on the right of the anchor. - // All three auto placements will add a vertical scrollbar if necessary. - // - _getTopLeft: function Flyout_getTopLeft() { - - var that = this; - - function configureVerticalWithScroll(anchor) { - // Won't fit top or bottom. Pick the one with the most space and add a scrollbar. - if (topHasMoreRoom(anchor)) { - // Top - that._adjustedHeight = spaceAbove(anchor) - that._verticalMarginBorderPadding; - that._nextTop = _Overlay._Overlay._keyboardInfo._visibleDocTop; - that._nextAnimOffset = AnimationOffsets.top; - } else { - // Bottom - that._adjustedHeight = spaceBelow(anchor) - that._verticalMarginBorderPadding; - that._nextTop = _Constants.pinToBottomEdge; - that._nextAnimOffset = AnimationOffsets.bottom; - } - that._doesScroll = true; - } - - // If the anchor is centered vertically, would the flyout fit above it? - function fitsVerticallyWithCenteredAnchor(anchor, flyout) { - // Returns true if the flyout would always fit at least top - // or bottom of its anchor, regardless of the position of the anchor, - // as long as the anchor never changed its height, nor did the height of - // the visualViewport change. - return ((_Overlay._Overlay._keyboardInfo._visibleDocHeight - anchor.height) / 2) >= flyout.totalHeight; - } - - function spaceAbove(anchor) { - return anchor.top - _Overlay._Overlay._keyboardInfo._visibleDocTop; - } - - function spaceBelow(anchor) { - return _Overlay._Overlay._keyboardInfo._visibleDocBottom - anchor.bottom; - } - - function topHasMoreRoom(anchor) { - return spaceAbove(anchor) > spaceBelow(anchor); - } - - // See if we can fit in various places, fitting in the main view, - // ignoring viewport changes, like for the IHM. - function fitTop(bottomConstraint, flyout) { - that._nextTop = bottomConstraint - flyout.totalHeight; - that._nextAnimOffset = AnimationOffsets.top; - return (that._nextTop >= _Overlay._Overlay._keyboardInfo._visibleDocTop && - that._nextTop + flyout.totalHeight <= _Overlay._Overlay._keyboardInfo._visibleDocBottom); - } - - function fitBottom(topConstraint, flyout) { - that._nextTop = topConstraint; - that._nextAnimOffset = AnimationOffsets.bottom; - return (that._nextTop >= _Overlay._Overlay._keyboardInfo._visibleDocTop && - that._nextTop + flyout.totalHeight <= _Overlay._Overlay._keyboardInfo._visibleDocBottom); - } - - function fitLeft(leftConstraint, flyout) { - that._nextLeft = leftConstraint - flyout.totalWidth; - that._nextAnimOffset = AnimationOffsets.left; - return (that._nextLeft >= 0 && that._nextLeft + flyout.totalWidth <= _Overlay._Overlay._keyboardInfo._visualViewportWidth); - } - - function fitRight(rightConstraint, flyout) { - that._nextLeft = rightConstraint; - that._nextAnimOffset = AnimationOffsets.right; - return (that._nextLeft >= 0 && that._nextLeft + flyout.totalWidth <= _Overlay._Overlay._keyboardInfo._visualViewportWidth); - } - - function centerVertically(anchor, flyout) { - that._nextTop = anchor.top + anchor.height / 2 - flyout.totalHeight / 2; - if (that._nextTop < _Overlay._Overlay._keyboardInfo._visibleDocTop) { - that._nextTop = _Overlay._Overlay._keyboardInfo._visibleDocTop; - } else if (that._nextTop + flyout.totalHeight >= _Overlay._Overlay._keyboardInfo._visibleDocBottom) { - // Flag to pin to bottom edge of visual document. - that._nextTop = _Constants.pinToBottomEdge; - } - } - - function alignHorizontally(anchor, flyout, alignment) { - if (alignment === "center") { - that._nextLeft = anchor.left + anchor.width / 2 - flyout.totalWidth / 2; - } else if (alignment === "left") { - that._nextLeft = anchor.left; - } else if (alignment === "right") { - that._nextLeft = anchor.right - flyout.totalWidth; - } else { - throw new _ErrorFromName("WinJS.UI.Flyout.BadAlignment", strings.badAlignment); - } - if (that._nextLeft < 0) { - that._nextLeft = 0; - } else if (that._nextLeft + flyout.totalWidth >= _Overlay._Overlay._keyboardInfo._visualViewportWidth) { - // Flag to pin to right edge of visible document. - that._nextLeft = _Constants.pinToRightEdge; - } - } - - var anchorRawRectangle, - flyout = {}, - anchor = {}; - - try { - anchorRawRectangle = this._currentAnchor.getBoundingClientRect(); - } - catch (e) { - throw new _ErrorFromName("WinJS.UI.Flyout.NoAnchor", strings.noAnchor); - } - - // Adjust for the anchor's margins. - anchor.top = anchorRawRectangle.top; - anchor.bottom = anchorRawRectangle.bottom; - anchor.left = anchorRawRectangle.left; - anchor.right = anchorRawRectangle.right; - anchor.height = anchor.bottom - anchor.top; - anchor.width = anchor.right - anchor.left; - - // Get our flyout and margins, note that getDimension calls - // window.getComputedStyle, which ensures layout is updated. - flyout.marginTop = getDimension(this._element, "marginTop"); - flyout.marginBottom = getDimension(this._element, "marginBottom"); - flyout.marginLeft = getDimension(this._element, "marginLeft"); - flyout.marginRight = getDimension(this._element, "marginRight"); - flyout.totalWidth = _ElementUtilities.getTotalWidth(this._element); - flyout.totalHeight = _ElementUtilities.getTotalHeight(this._element); - flyout.contentWidth = _ElementUtilities.getContentWidth(this._element); - flyout.contentHeight = _ElementUtilities.getContentHeight(this._element); - this._verticalMarginBorderPadding = (flyout.totalHeight - flyout.contentHeight); - this._adjustedHeight = flyout.contentHeight; - - // Check fit for requested this._currentPlacement, doing fallback if necessary - switch (this._currentPlacement) { - case "top": - if (!fitTop(anchor.top, flyout)) { - // Didn't fit, needs scrollbar - this._nextTop = _Overlay._Overlay._keyboardInfo._visibleDocTop; - this._doesScroll = true; - this._adjustedHeight = spaceAbove(anchor) - this._verticalMarginBorderPadding; - } - alignHorizontally(anchor, flyout, this._currentAlignment); - break; - case "bottom": - if (!fitBottom(anchor.bottom, flyout)) { - // Didn't fit, needs scrollbar - this._nextTop = _Constants.pinToBottomEdge; - this._doesScroll = true; - this._adjustedHeight = spaceBelow(anchor) - this._verticalMarginBorderPadding; - } - alignHorizontally(anchor, flyout, this._currentAlignment); - break; - case "left": - if (!fitLeft(anchor.left, flyout)) { - // Didn't fit, just shove it to edge - this._nextLeft = 0; - } - centerVertically(anchor, flyout); - break; - case "right": - if (!fitRight(anchor.right, flyout)) { - // Didn't fit, just shove it to edge - this._nextLeft = _Constants.pinToRightEdge; - } - centerVertically(anchor, flyout); - break; - case "autovertical": - if (!fitTop(anchor.top, flyout)) { - // Didn't fit above (preferred), so go below. - if (!fitBottom(anchor.bottom, flyout)) { - // Didn't fit, needs scrollbar - configureVerticalWithScroll(anchor); - } - } - alignHorizontally(anchor, flyout, this._currentAlignment); - break; - case "autohorizontal": - if (!fitLeft(anchor.left, flyout)) { - // Didn't fit left (preferred), so go right. - if (!fitRight(anchor.right, flyout)) { - // Didn't fit,just shove it to edge - this._nextLeft = _Constants.pinToRightEdge; - } - } - centerVertically(anchor, flyout); - break; - case "auto": - // Auto, if the anchor was in the vertical center of the display would we fit above it? - if (fitsVerticallyWithCenteredAnchor(anchor, flyout)) { - // It will fit above or below the anchor - if (!fitTop(anchor.top, flyout)) { - // Didn't fit above (preferred), so go below. - fitBottom(anchor.bottom, flyout); - } - alignHorizontally(anchor, flyout, this._currentAlignment); - } else { - // Won't fit above or below, try a side - if (!fitLeft(anchor.left, flyout) && - !fitRight(anchor.right, flyout)) { - // Didn't fit left or right either - configureVerticalWithScroll(anchor); - alignHorizontally(anchor, flyout, this._currentAlignment); - } else { - centerVertically(anchor, flyout); - } - } - break; - case "_cascade": - // Align vertically - // PREFERRED: When there is enough room to align a subMenu to either the top or the bottom of its - // anchor element, the subMenu prefers to be top aligned. - // FALLBACK: When there is enough room to bottom align a subMenu but not enough room to top align it, - // then the subMenu will align to the bottom of its anchor element. - // LASTRESORT: When there is not enough room to top align or bottom align the subMenu to its anchor, - // then the subMenu will be center aligned to it's anchor's vertical midpoint. - if (!fitBottom(anchor.top - flyout.marginTop, flyout) && !fitTop(anchor.bottom + flyout.marginBottom, flyout)) { - centerVertically(anchor, flyout); - } - // Determine horizontal direction - // PREFERRED: When there is enough room to fit a subMenu on either side of the anchor, - // the subMenu prefers to go on the right hand side. - // FALLBACK: When there is only enough room to fit a subMenu on the left side of the anchor, - // the subMenu is placed to the left of the parent menu. - // LASTRESORT: When there is not enough room to fit a subMenu on either side of the anchor, - // the subMenu is pinned to the right edge of the window. - var rtl = _Global.getComputedStyle(this._element).direction === "rtl"; - - // Cascading Menus should overlap their ancestor menu by 4 pixels and we have a unit test to - // verify that behavior. Because we don't have access to the ancestor flyout we need to specify - // the overlap in terms of our anchor element. There is a 1px border around the menu that - // contains our anchor we need to overlap our anchor by 3px to ensure that we overlap the containing - // Menu by 4px. - var pixelsToOverlapAnchor = 3; - - var beginRight = anchor.right - flyout.marginLeft - pixelsToOverlapAnchor; - var beginLeft = anchor.left + flyout.marginRight + pixelsToOverlapAnchor; - - if (rtl) { - if (!fitLeft(beginLeft, flyout) && !fitRight(beginRight, flyout)) { - // Doesn't fit on either side, pin to the left edge. - that._nextLeft = 0; - that._nextAnimOffset = AnimationOffsets.left; - } - } else { - if (!fitRight(beginRight, flyout) && !fitLeft(beginLeft, flyout)) { - // Doesn't fit on either side, pin to the right edge of the visible document. - that._nextLeft = _Constants.pinToRightEdge; - that._nextAnimOffset = AnimationOffsets.right; - } - } - - break; - default: - // Not a legal this._currentPlacement value - throw new _ErrorFromName("WinJS.UI.Flyout.BadPlacement", strings.badPlacement); - } - }, - - _clearAdjustedStyles: function Flyout_clearAdjustedStyles() { - // Move to 0,0 in case it is off screen, so that it lays out at a reasonable size - this._element.style.top = "0px"; - this._element.style.bottom = "auto"; - this._element.style.left = "0px"; - this._element.style.right = "auto"; - - // Clear height restrictons and scrollbar class - _ElementUtilities.removeClass(this._element, _Constants.scrollsClass); - if (this._lastMaxHeight !== null) { - this._element.style.maxHeight = this._lastMaxHeight; - this._lastMaxHeight = null; - } - - // Clear Alignment - _ElementUtilities.removeClass(this._element, "win-rightalign"); - _ElementUtilities.removeClass(this._element, "win-leftalign"); - }, - - _setAlignment: function Flyout_setAlignment(alignment) { - // Alignment - switch (alignment) { - case "left": - _ElementUtilities.addClass(this._element, "win-leftalign"); - break; - case "right": - _ElementUtilities.addClass(this._element, "win-rightalign"); - break; - case "center": - case "none": - break; - } - }, - - _showingKeyboard: function Flyout_showingKeyboard(event) { - if (this.hidden) { - return; - } - - // The only way that we can be showing a keyboard when a flyout is up is because the input was - // in the flyout itself, in which case we'll be moving ourselves. There is no practical way - // for the application to override this as the focused element is in our flyout. - event.ensuredFocusedElementInView = true; - - // See if the keyboard is going to force us to move - this._checkKeyboardFit(); - - if (this._keyboardMovedUs) { - // Pop out immediately, then move to new spot - this._element.style.opacity = 0; - var that = this; - _Global.setTimeout(function () { that._adjustForKeyboard(); that._baseAnimateIn(); }, _Overlay._Overlay._keyboardInfo._animationShowLength); - } - }, - - _resize: function Flyout_resize() { - // If hidden and not busy animating, then nothing to do - if (!this.hidden || this._animating) { - - // This should only happen if the IHM is dismissing, - // the only other way is for viewstate changes, which - // would dismiss any flyout. - if (this._needToHandleHidingKeyboard) { - // Hiding keyboard, update our position, giving the anchor a chance to update first. - var that = this; - _BaseUtils._setImmediate(function () { - if (!that.hidden || that._animating) { - that._findPosition(); - } - }); - this._needToHandleHidingKeyboard = false; - } - } - }, - - // If you were not pinned to the bottom, you might have to be now. - _checkKeyboardFit: function Flyout_checkKeyboardFit() { - // Special Flyout positioning rules to determine if the Flyout needs to adjust its - // position because of the IHM. If the Flyout needs to adjust for the IHM, it will reposition - // itself to be pinned to either the top or bottom edge of the visual viewport. - // - Too Tall, above top, or below bottom. - - var keyboardMovedUs = false; - var viewportHeight = _Overlay._Overlay._keyboardInfo._visibleDocHeight; - var adjustedMarginBoxHeight = this._adjustedHeight + this._verticalMarginBorderPadding; - if (adjustedMarginBoxHeight > viewportHeight) { - // The Flyout is now too tall to fit in the viewport, pin to top and adjust height. - keyboardMovedUs = true; - this._nextTop = _Constants.pinToBottomEdge; - this._adjustedHeight = viewportHeight - this._verticalMarginBorderPadding; - this._doesScroll = true; - } else if (this._nextTop >= 0 && - this._nextTop + adjustedMarginBoxHeight > _Overlay._Overlay._keyboardInfo._visibleDocBottom) { - // Flyout clips the bottom of the viewport. Pin to bottom. - this._nextTop = _Constants.pinToBottomEdge; - keyboardMovedUs = true; - } else if (this._nextTop === _Constants.pinToBottomEdge) { - // We were already pinned to the bottom, so our position on screen will change - keyboardMovedUs = true; - } - - // Signals use of basic fadein animation - this._keyboardMovedUs = keyboardMovedUs; - }, - - _adjustForKeyboard: function Flyout_adjustForKeyboard() { - // Keyboard moved us, update our metrics as needed - if (this._doesScroll) { - // Add scrollbar if we didn't already have scrollsClass - if (!this._lastMaxHeight) { - _ElementUtilities.addClass(this._element, _Constants.scrollsClass); - this._lastMaxHeight = this._element.style.maxHeight; - } - // Adjust height - this._element.style.maxHeight = this._adjustedHeight + "px"; - } - - // Update top/bottom - this._checkScrollPosition(true); - }, - - _hidingKeyboard: function Flyout_hidingKeyboard() { - // If we aren't visible and not animating, or haven't been repositioned, then nothing to do - // We don't know if the keyboard moved the anchor, so _keyboardMovedUs doesn't help here - if (!this.hidden || this._animating) { - - // Snap to the final position - // We'll either just reveal the current space or resize the window - if (_Overlay._Overlay._keyboardInfo._isResized) { - // Flag resize that we'll need an updated position - this._needToHandleHidingKeyboard = true; - } else { - // Not resized, update our final position, giving the anchor a chance to update first. - var that = this; - _BaseUtils._setImmediate(function () { - if (!that.hidden || that._animating) { - that._findPosition(); - } - }); - } - } - }, - - _checkScrollPosition: function Flyout_checkScrollPosition(showing) { - if (this.hidden && !showing) { - return; - } - - // May need to adjust top by viewport offset - if (this._nextTop < 0) { - // Need to attach to bottom - this._element.style.bottom = _Overlay._Overlay._keyboardInfo._visibleDocBottomOffset + "px"; - this._element.style.top = "auto"; - } else { - // Normal, attach to top - this._element.style.top = this._nextTop + "px"; - this._element.style.bottom = "auto"; - } - }, - - // AppBar flyout animations - _flyoutAnimateIn: function Flyout_flyoutAnimateIn() { - if (this._keyboardMovedUs) { - return this._baseAnimateIn(); - } else { - this._element.style.opacity = 1; - this._element.style.visibility = "visible"; - return Animations.showPopup(this._element, this._nextAnimOffset); - } - }, - - _flyoutAnimateOut: function Flyout_flyoutAnimateOut() { - if (this._keyboardMovedUs) { - return this._baseAnimateOut(); - } else { - this._element.style.opacity = 0; - return Animations.hidePopup(this._element, this._nextAnimOffset); - } - }, - - // Hide all other flyouts besides this one - _hideAllOtherFlyouts: function Flyout_hideAllOtherFlyouts(thisFlyout) { - var flyouts = _Global.document.querySelectorAll("." + _Constants.flyoutClass); - for (var i = 0; i < flyouts.length; i++) { - var flyoutControl = flyouts[i].winControl; - if (flyoutControl && !flyoutControl.hidden && (flyoutControl !== thisFlyout)) { - flyoutControl.hide(); - } - } - }, - - _handleKeyDown: function Flyout_handleKeyDown(event) { - if ((event.keyCode === Key.space || event.keyCode === Key.enter) - && (this === _Global.document.activeElement)) { - event.preventDefault(); - event.stopPropagation(); - this.winControl.hide(); - } else if (event.shiftKey && event.keyCode === Key.tab - && this === _Global.document.activeElement - && !event.altKey && !event.ctrlKey && !event.metaKey) { - event.preventDefault(); - event.stopPropagation(); - this.winControl._focusOnLastFocusableElementOrThis(); - } - }, - - _handleFocusIn: function Flyout_handleFocusIn(event) { - if (!this.element.contains(event.relatedTarget)) { - Flyout._cascadeManager.handleFocusIntoFlyout(event); - } - // Else focus is only moving between elements in the flyout. - // Doesn't need to be handled by cascadeManager. - }, - - // Create and add a new first div as the first child - _addFirstDiv: function Flyout_addFirstDiv() { - var firstDiv = _Global.document.createElement("div"); - firstDiv.className = _Constants.firstDivClass; - firstDiv.style.display = "inline"; - firstDiv.setAttribute("role", "menuitem"); - firstDiv.setAttribute("aria-hidden", "true"); - - // add to beginning - if (this._element.children[0]) { - this._element.insertBefore(firstDiv, this._element.children[0]); - } else { - this._element.appendChild(firstDiv); - } - - var that = this; - _ElementUtilities._addEventListener(firstDiv, "focusin", function () { that._focusOnLastFocusableElementOrThis(); }, false); - - return firstDiv; - }, - - // Create and add a new final div as the last child - _addFinalDiv: function Flyout_addFinalDiv() { - var finalDiv = _Global.document.createElement("div"); - finalDiv.className = _Constants.finalDivClass; - finalDiv.style.display = "inline"; - finalDiv.setAttribute("role", "menuitem"); - finalDiv.setAttribute("aria-hidden", "true"); - - this._element.appendChild(finalDiv); - var that = this; - _ElementUtilities._addEventListener(finalDiv, "focusin", function () { that._focusOnFirstFocusableElementOrThis(); }, false); - - return finalDiv; - }, - - _writeProfilerMark: function Flyout_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI.Flyout:" + this._id + ":" + text); - } - }, - { - _cascadeManager: new _CascadeManager(), - }); - return Flyout; - }) - }); - -}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/CommandingSurface/_Constants',["require", "exports"], function (require, exports) { - // CommandingSurface class names - exports.ClassNames = { - controlCssClass: "win-commandingsurface", - disposableCssClass: "win-disposable", - actionAreaCssClass: "win-commandingsurface-actionarea", - actionAreaContainerCssClass: "win-commandingsurface-actionareacontainer", - overflowButtonCssClass: "win-commandingsurface-overflowbutton", - spacerCssClass: "win-commandingsurface-spacer", - ellipsisCssClass: "win-commandingsurface-ellipsis", - overflowAreaCssClass: "win-commandingsurface-overflowarea", - overflowAreaContainerCssClass: "win-commandingsurface-overflowareacontainer", - contentFlyoutCssClass: "win-commandingsurface-contentflyout", - emptyCommandingSurfaceCssClass: "win-commandingsurface-empty", - menuCssClass: "win-menu", - menuContainsToggleCommandClass: "win-menu-containstogglecommand", - openedClass: "win-commandingsurface-opened", - closingClass: "win-commandingsurface-closing", - closedClass: "win-commandingsurface-closed", - noneClass: "win-commandingsurface-closeddisplaynone", - minimalClass: "win-commandingsurface-closeddisplayminimal", - compactClass: "win-commandingsurface-closeddisplaycompact", - fullClass: "win-commandingsurface-closeddisplayfull", - overflowTopClass: "win-commandingsurface-overflowtop", - overflowBottomClass: "win-commandingsurface-overflowbottom", - }; - exports.EventNames = { - beforeOpen: "beforeopen", - afterOpen: "afteropen", - beforeClose: "beforeclose", - afterClose: "afterclose", - commandPropertyMutated: "_commandpropertymutated", - }; - exports.actionAreaCommandWidth = 68; - exports.actionAreaSeparatorWidth = 34; - exports.actionAreaOverflowButtonWidth = 32; - exports.overflowCommandHeight = 44; - exports.overflowSeparatorHeight = 12; - exports.controlMinWidth = exports.actionAreaOverflowButtonWidth; - exports.overflowAreaMaxWidth = 480; - exports.heightOfMinimal = 24; - exports.heightOfCompact = 48; - exports.contentMenuCommandDefaultLabel = "Custom content"; - exports.defaultClosedDisplayMode = "compact"; - exports.defaultOpened = false; - exports.defaultOverflowDirection = "bottom"; - // Constants for commands - exports.typeSeparator = "separator"; - exports.typeContent = "content"; - exports.typeButton = "button"; - exports.typeToggle = "toggle"; - exports.typeFlyout = "flyout"; - exports.commandSelector = ".win-command"; - exports.primaryCommandSection = "primary"; - exports.secondaryCommandSection = "secondary"; -}); - -define('WinJS/Controls/ToolBar/_Constants',["require", "exports", "../CommandingSurface/_Constants"], function (require, exports, _CommandingSurfaceConstants) { - // toolbar class names - exports.ClassNames = { - controlCssClass: "win-toolbar", - disposableCssClass: "win-disposable", - actionAreaCssClass: "win-toolbar-actionarea", - overflowButtonCssClass: "win-toolbar-overflowbutton", - spacerCssClass: "win-toolbar-spacer", - ellipsisCssClass: "win-toolbar-ellipsis", - overflowAreaCssClass: "win-toolbar-overflowarea", - contentFlyoutCssClass: "win-toolbar-contentflyout", - emptytoolbarCssClass: "win-toolbar-empty", - menuCssClass: "win-menu", - menuContainsToggleCommandClass: "win-menu-containstogglecommand", - openedClass: "win-toolbar-opened", - closedClass: "win-toolbar-closed", - compactClass: "win-toolbar-closeddisplaycompact", - fullClass: "win-toolbar-closeddisplayfull", - overflowTopClass: "win-toolbar-overflowtop", - overflowBottomClass: "win-toolbar-overflowbottom", - placeHolderCssClass: "win-toolbar-placeholder", - }; - exports.EventNames = { - beforeOpen: "beforeopen", - afterOpen: "afteropen", - beforeClose: "beforeclose", - afterClose: "afterclose" - }; - exports.OverflowDirection = { - top: "top", - bottom: "bottom", - }; - exports.overflowAreaMaxWidth = _CommandingSurfaceConstants.overflowAreaMaxWidth; - exports.controlMinWidth = _CommandingSurfaceConstants.controlMinWidth; - exports.defaultClosedDisplayMode = "compact"; - exports.defaultOpened = false; - // Constants for commands - exports.typeSeparator = "separator"; - exports.typeContent = "content"; - exports.typeButton = "button"; - exports.typeToggle = "toggle"; - exports.typeFlyout = "flyout"; - exports.commandSelector = ".win-command"; - exports.primaryCommandSection = "primary"; - exports.secondaryCommandSection = "secondary"; -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -// Glyph Enumeration -/// Segoe -define('WinJS/Controls/AppBar/_Icon',[ - 'exports', - '../../Core/_Base', - '../../Core/_Resources' - ], function appBarIconInit(exports, _Base, _Resources) { - "use strict"; - - var glyphs = ["previous", - "next", - "play", - "pause", - "edit", - "save", - "clear", - "delete", - "remove", - "add", - "cancel", - "accept", - "more", - "redo", - "undo", - "home", - "up", - "forward", - "right", - "back", - "left", - "favorite", - "camera", - "settings", - "video", - "sync", - "download", - "mail", - "find", - "help", - "upload", - "emoji", - "twopage", - "leavechat", - "mailforward", - "clock", - "send", - "crop", - "rotatecamera", - "people", - "closepane", - "openpane", - "world", - "flag", - "previewlink", - "globe", - "trim", - "attachcamera", - "zoomin", - "bookmarks", - "document", - "protecteddocument", - "page", - "bullets", - "comment", - "mail2", - "contactinfo", - "hangup", - "viewall", - "mappin", - "phone", - "videochat", - "switch", - "contact", - "rename", - "pin", - "musicinfo", - "go", - "keyboard", - "dockleft", - "dockright", - "dockbottom", - "remote", - "refresh", - "rotate", - "shuffle", - "list", - "shop", - "selectall", - "orientation", - "import", - "importall", - "browsephotos", - "webcam", - "pictures", - "savelocal", - "caption", - "stop", - "showresults", - "volume", - "repair", - "message", - "page2", - "calendarday", - "calendarweek", - "calendar", - "characters", - "mailreplyall", - "read", - "link", - "accounts", - "showbcc", - "hidebcc", - "cut", - "attach", - "paste", - "filter", - "copy", - "emoji2", - "important", - "mailreply", - "slideshow", - "sort", - "manage", - "allapps", - "disconnectdrive", - "mapdrive", - "newwindow", - "openwith", - "contactpresence", - "priority", - "uploadskydrive", - "gototoday", - "font", - "fontcolor", - "contact2", - "folder", - "audio", - "placeholder", - "view", - "setlockscreen", - "settile", - "cc", - "stopslideshow", - "permissions", - "highlight", - "disableupdates", - "unfavorite", - "unpin", - "openlocal", - "mute", - "italic", - "underline", - "bold", - "movetofolder", - "likedislike", - "dislike", - "like", - "alignright", - "aligncenter", - "alignleft", - "zoom", - "zoomout", - "openfile", - "otheruser", - "admin", - "street", - "map", - "clearselection", - "fontdecrease", - "fontincrease", - "fontsize", - "cellphone", - "reshare", - "tag", - "repeatone", - "repeatall", - "outlinestar", - "solidstar", - "calculator", - "directions", - "target", - "library", - "phonebook", - "memo", - "microphone", - "postupdate", - "backtowindow", - "fullscreen", - "newfolder", - "calendarreply", - "unsyncfolder", - "reporthacked", - "syncfolder", - "blockcontact", - "switchapps", - "addfriend", - "touchpointer", - "gotostart", - "zerobars", - "onebar", - "twobars", - "threebars", - "fourbars", - "scan", - "preview", - "hamburger"]; - - // Provide properties to grab resources for each of the icons - /// - /// The AppBarIcon enumeration provides a set of glyphs for use with the AppBarCommand icon property. - /// - var icons = glyphs.reduce(function (fixedIcons, item) { - fixedIcons[item] = { get: function () { return _Resources._getWinJSString("ui/appBarIcons/" + item).value; } }; - return fixedIcons; - }, {}); - - _Base.Namespace._moduleDefine(exports, "WinJS.UI.AppBarIcon", icons); -}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -// AppBarCommand -/// appbar,appbars,Flyout,Flyouts,onclick,Statics -define('WinJS/Controls/AppBar/_Command',[ - 'exports', - '../../Core/_Global', - '../../Core/_WinRT', - '../../Core/_Base', - "../../Core/_BaseUtils", - '../../Core/_ErrorFromName', - "../../Core/_Events", - '../../Core/_Resources', - '../../Utilities/_Control', - '../../Utilities/_Dispose', - '../../Utilities/_ElementUtilities', - '../Flyout/_Overlay', - '../Tooltip', - '../_LegacyAppBar/_Constants', - './_Icon' -], function appBarCommandInit(exports, _Global, _WinRT, _Base, _BaseUtils, _ErrorFromName, _Events, _Resources, _Control, _Dispose, _ElementUtilities, _Overlay, Tooltip, _Constants, _Icon) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// - /// Represents a command to display in an AppBar. - /// - /// - /// - /// - /// ]]> - /// Raised after the hidden property has been programmatically changed. - /// The AppBarCommand control itself. - /// The AppBarCommand's icon box. - /// The AppBarCommand's icon's image formatting. - /// The AppBarCommand's label - /// - /// - AppBarCommand: _Base.Namespace._lazy(function () { - - function _handleClick(event) { - /*jshint validthis: true */ - var command = this.winControl; - if (command) { - if (command._type === _Constants.typeToggle) { - command.selected = !command.selected; - } else if (command._type === _Constants.typeFlyout && command._flyout) { - var flyout = command._flyout; - // Flyout may not have processAll'd, so this may be a DOM object - if (typeof flyout === "string") { - flyout = _Global.document.getElementById(flyout); - } - if (!flyout.show) { - flyout = flyout.winControl; - } - if (flyout && flyout.show) { - flyout.show(this, "autovertical"); - } - } - if (command.onclick) { - command.onclick(event); - } - } - } - - // Used by AppBarCommands to notify listeners that a property has changed. - var PropertyMutations = _Base.Class.define(function PropertyMutations_ctor() { - this._observer = _BaseUtils._merge({}, _Events.eventMixin); - }, { - bind: function (callback) { - this._observer.addEventListener(_Constants.commandPropertyMutated, callback); - }, - unbind: function (callback) { - this._observer.removeEventListener(_Constants.commandPropertyMutated, callback); - }, - dispatchEvent: function (type, detail) { - this._observer.dispatchEvent(type, detail); - }, - }); - - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/appBarCommandAriaLabel").value; }, - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get badClick() { return "Invalid argument: The onclick property for an {0} must be a function"; }, - get badDivElement() { return "Invalid argument: For a content command, the element must be null or a div element"; }, - get badHrElement() { return "Invalid argument: For a separator, the element must be null or an hr element"; }, - get badButtonElement() { return "Invalid argument: For a button, toggle, or flyout command, the element must be null or a button element"; }, - get badPriority() { return "Invalid argument: the priority of an {0} must be a non-negative integer"; } - }; - - var AppBarCommand = _Base.Class.define(function AppBarCommand_ctor(element, options) { - /// - /// - /// Creates a new AppBarCommand control. - /// - /// - /// The DOM element that will host the control. AppBarCommand will create one if null. - /// - /// - /// The set of properties and values to apply to the new AppBarCommand. - /// - /// - /// The new AppBarCommand control. - /// - /// - - // Check to make sure we weren't duplicated - if (element && element.winControl) { - throw new _ErrorFromName("WinJS.UI.AppBarCommand.DuplicateConstruction", strings.duplicateConstruction); - } - - this._disposed = false; - - // Don't blow up if they didn't pass options - if (!options) { - options = {}; - } - - // Need a type before we can create our element - if (!options.type) { - this._type = _Constants.typeButton; - } - - options.section = options.section || _Constants.sectionPrimary; - - // Go ahead and create it, separator and content types look different than buttons - // Don't forget to use passed in element if one was provided. - this._element = element; - - if (options.type === _Constants.typeContent) { - this._createContent(); - } else if (options.type === _Constants.typeSeparator) { - this._createSeparator(); - } else { - // This will also set the icon & label - this._createButton(); - } - _ElementUtilities.addClass(this._element, "win-disposable"); - - // Remember ourselves - this._element.winControl = this; - - // Attach our css class - _ElementUtilities.addClass(this._element, _Constants.appBarCommandClass); - - if (options.onclick) { - this.onclick = options.onclick; - } - // We want to handle some clicks - options.onclick = _handleClick; - - _Control.setOptions(this, options); - - if (this._type === _Constants.typeToggle && !options.selected) { - this.selected = false; - } - - // Set up pointerdown handler and clean up ARIA if needed - if (this._type !== _Constants.typeSeparator) { - - // Make sure we have an ARIA role - var role = this._element.getAttribute("role"); - if (role === null || role === "" || role === undefined) { - if (this._type === _Constants.typeToggle) { - role = "menuitemcheckbox"; - } else if (this._type === _Constants.typeContent) { - role = "group"; - } else { - role = "menuitem"; - } - this._element.setAttribute("role", role); - if (this._type === _Constants.typeFlyout) { - this._element.setAttribute("aria-haspopup", true); - } - } - // Label should've been set by label, but if it was missed for some reason: - var label = this._element.getAttribute("aria-label"); - if (label === null || label === "" || label === undefined) { - this._element.setAttribute("aria-label", strings.ariaLabel); - } - } - - this._propertyMutations = new PropertyMutations(); - var that = this; - ObservablePropertyWhiteList.forEach(function (propertyName) { - makeObservable(that, propertyName); - }); - }, { - /// - /// Gets or sets the ID of the AppBarCommand. - /// - id: { - get: function () { - return this._element.id; - }, - - set: function (value) { - // we allow setting first time only. otherwise we ignore it. - if (value && !this._element.id) { - this._element.id = value; - } - } - }, - - /// - /// Gets or sets the type of the AppBarCommand. Possible values are "button", "toggle", "flyout", "content" or "separator". - /// - type: { - get: function () { - return this._type; - }, - set: function (value) { - // we allow setting first time only. otherwise we ignore it. - if (!this._type) { - if (value !== _Constants.typeContent && value !== _Constants.typeFlyout && value !== _Constants.typeToggle && value !== _Constants.typeSeparator) { - this._type = _Constants.typeButton; - } else { - this._type = value; - } - } - } - }, - - /// - /// Gets or sets the label of the AppBarCommand. - /// - label: { - get: function () { - return this._label; - }, - set: function (value) { - this._label = value; - if (this._labelSpan) { - this._labelSpan.textContent = this.label; - } - - // Ensure that we have a tooltip, by updating already-constructed tooltips. Separators won't have these: - if (!this.tooltip && this._tooltipControl) { - this._tooltip = this.label; - this._tooltipControl.innerHTML = this.label; - } - - // Update aria-label - this._element.setAttribute("aria-label", this.label); - - // Check if we need to suppress the tooltip - this._testIdenticalTooltip(); - } - }, - - /// - /// Gets or sets the icon of the AppBarCommand. - /// - icon: { - get: function () { - return this._icon; - }, - set: function (value) { - - this._icon = _Icon[value] || value; - - if (this._imageSpan) { - // If the icon's a single character, presume a glyph - if (this._icon && this._icon.length === 1) { - // Set the glyph - this._imageSpan.textContent = this._icon; - this._imageSpan.style.backgroundImage = ""; - this._imageSpan.style.msHighContrastAdjust = ""; - _ElementUtilities.addClass(this._imageSpan, "win-commandglyph"); - } else { - // Must be an image, set that - this._imageSpan.textContent = ""; - this._imageSpan.style.backgroundImage = this._icon; - this._imageSpan.style.msHighContrastAdjust = "none"; - _ElementUtilities.removeClass(this._imageSpan, "win-commandglyph"); - } - } - } - }, - - /// - /// Gets or sets the function to invoke when the command is clicked. - /// - onclick: { - get: function () { - return this._onclick; - }, - set: function (value) { - if (value && typeof value !== "function") { - throw new _ErrorFromName("WinJS.UI.AppBarCommand.BadClick", _Resources._formatString(strings.badClick, "AppBarCommand")); - } - this._onclick = value; - } - }, - - /// - /// Gets or sets the priority of the command - /// - priority: { - get: function () { - return this._priority; - }, - set: function (value) { - if (value === undefined || (typeof value === "number" && value >= 0)) { - this._priority = value; - } else { - throw new _ErrorFromName("WinJS.UI.AppBarCommand.BadPriority", _Resources._formatString(strings.badPriority, "AppBarCommand")); - } - - } - }, - - /// - /// For flyout-type AppBarCommands, this property returns the WinJS.UI.Flyout that this command invokes. - /// When setting this property, you may also use the String ID of the flyout to invoke, the DOM object - /// for the flyout, or the WinJS.UI.Flyout object itself. - /// If the value is set to the String ID of the flyout to invoke, or the DOM object for the flyout, but this - /// has not been processed yet, the getter will return the DOM object until it is processed, and - /// subsequently return a flyout. - /// - flyout: { - get: function () { - // Resolve it to the flyout - var flyout = this._flyout; - if (typeof flyout === "string") { - flyout = _Global.document.getElementById(flyout); - } - // If it doesn't have a .element, then we need to getControl on it - if (flyout && !flyout.element && flyout.winControl) { - flyout = flyout.winControl; - } - - return flyout; - }, - set: function (value) { - // Need to update aria-owns with the new ID. - var id = value; - if (id && typeof id !== "string") { - // Our controls have .element properties - if (id.element) { - id = id.element; - } - // Hope it's a DOM element, get ID from DOM element - if (id) { - if (id.id) { - id = id.id; - } else { - // No id, have to fake one - id.id = _ElementUtilities._uniqueID(id); - id = id.id; - } - } - } - if (typeof id === "string") { - this._element.setAttribute("aria-owns", id); - } - - // Remember it - this._flyout = value; - } - }, - - /// - /// Gets or sets the section that the AppBarCommand is in. Possible values are "secondary" and "primary". - /// - section: { - get: function () { - return this._section; - }, - set: function (value) { - // we allow settings section only one time - if (!this._section || _WinRT.Windows.ApplicationModel.DesignMode.designModeEnabled) { - this._setSection(value); - } - } - }, - - /// Gets or sets the tooltip text of the AppBarCommand. - tooltip: { - get: function () { - return this._tooltip; - }, - set: function (value) { - this._tooltip = value; - - // Update already-constructed tooltips. Separators and content commands won't have these: - if (this._tooltipControl) { - this._tooltipControl.innerHTML = this._tooltip; - } - - // Check if we need to suppress the tooltip - this._testIdenticalTooltip(); - } - }, - - /// Set or get the selected state of a toggle button. - selected: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return this._element.getAttribute("aria-checked") === "true"; - }, - set: function (value) { - this._element.setAttribute("aria-checked", value); - } - }, - - /// - element: { - get: function () { - return this._element; - } - }, - - /// - /// Gets or sets a value that indicates whether the AppBarCommand is disabled. A value of true disables the AppBarCommand, and a value of false enables it. - /// - disabled: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return !!this._element.disabled; - }, - set: function (value) { - this._element.disabled = value; - } - }, - - /// - hidden: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return this._element.style.visibility === "hidden"; - }, - set: function (value) { - if (value === this.hidden) { - // No changes to make. - return; - } - - var style = this._element.style; - var originalVisibility = style.visibility; - var originalDisplay = style.display; - - if (value) { - style.visibility = "hidden"; - style.display = "none"; - } else { - style.visibility = ""; - style.display = "inline-block"; - } - - if (!this._sendEvent(_Constants.commandVisibilityChanged)) { - style.visibility = originalVisibility; - style.display = originalDisplay; - } - } - }, - - /// - /// Gets or sets the HTMLElement within a "content" type AppBarCommand that should receive focus whenever focus moves via Home or the arrow keys, - /// from the previous AppBarCommand to the this AppBarCommand. Returns the AppBarCommand object's host element by default. - /// - firstElementFocus: { - get: function () { - return this._firstElementFocus || this._lastElementFocus || this._element; - }, - set: function (element) { - // Arguments of null and this.element should treated the same to ensure that this.element is never a tabstop when either focus property has been set. - this._firstElementFocus = (element === this.element) ? null : element; - this._updateTabStop(); - } - }, - - /// - /// Gets or sets the HTMLElement within a "content" type AppBarCommand that should receive focus whenever focus would move, via End or arrow keys, - /// from the next AppBarCommand to this AppBarCommand. Returns this AppBarCommand object's host element by default. - /// - lastElementFocus: { - get: function () { - return this._lastElementFocus || this._firstElementFocus || this._element; - }, - set: function (element) { - // Arguments of null and this.element should treated the same to ensure that this.element is never a tabstop when either focus property has been set. - this._lastElementFocus = (element === this.element) ? null : element; - this._updateTabStop(); - } - }, - - dispose: function () { - /// - /// - /// Disposes this control. - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - - if (this._tooltipControl) { - this._tooltipControl.dispose(); - } - - if (this._type === _Constants.typeContent) { - _Dispose.disposeSubTree(this.element); - } - }, - - addEventListener: function (type, listener, useCapture) { - /// - /// - /// Registers an event handler for the specified event. - /// - /// - /// Required. The name of the event to register. - /// - /// Required. The event handler function to associate with this event. - /// - /// Optional. Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - /// - /// - return this._element.addEventListener(type, listener, useCapture); - }, - - removeEventListener: function (type, listener, useCapture) { - /// - /// - /// Removes an event handler that the addEventListener method registered. - /// - /// Required. The name of the event to remove. - /// Required. The event handler function to remove. - /// - /// Optional. Set to true to remove the capturing phase event handler; otherwise, set to false to remove the bubbling phase event handler. - /// - /// - return this._element.removeEventListener(type, listener, useCapture); - }, - - /// Adds an extra CSS class during construction. - extraClass: { - get: function () { - return this._extraClass; - }, - set: function (value) { - if (this._extraClass) { - _ElementUtilities.removeClass(this._element, this._extraClass); - } - this._extraClass = value; - _ElementUtilities.addClass(this._element, this._extraClass); - } - }, - - // Private - _testIdenticalTooltip: function AppBarCommand_testIdenticalToolTip() { - this._hideIfFullSize = (this._label === this._tooltip); - }, - - _createContent: function AppBarCommand_createContent() { - // Make sure there's an element - if (!this._element) { - this._element = _Global.document.createElement("div"); - } else { - // Verify the element was a div - if (this._element.tagName !== "DIV") { - throw new _ErrorFromName("WinJS.UI.AppBarCommand.BadDivElement", strings.badDivElement); - } - } - - // If a tabIndex isnt set, default to 0; - if (parseInt(this._element.getAttribute("tabIndex"), 10) !== this._element.tabIndex) { - this._element.tabIndex = 0; - } - }, - - _createSeparator: function AppBarCommand_createSeparator() { - // Make sure there's an element - if (!this._element) { - this._element = _Global.document.createElement("hr"); - } else { - // Verify the element was an hr - if (this._element.tagName !== "HR") { - throw new _ErrorFromName("WinJS.UI.AppBarCommand.BadHrElement", strings.badHrElement); - } - } - }, - - _createButton: function AppBarCommand_createButton() { - // Make sure there's an element - if (!this._element) { - this._element = _Global.document.createElement("button"); - } else { - // Verify the element was a button - if (this._element.tagName !== "BUTTON") { - throw new _ErrorFromName("WinJS.UI.AppBarCommand.BadButtonElement", strings.badButtonElement); - } - // Make sure it has a type="button" - var type = this._element.getAttribute("type"); - if (type === null || type === "" || type === undefined) { - this._element.setAttribute("type", "button"); - } - this._element.innerHTML = ""; - } - - // AppBarCommand buttons need to look like this: - //// - this._element.type = "button"; - this._iconSpan = _Global.document.createElement("span"); - this._iconSpan.setAttribute("aria-hidden", "true"); - this._iconSpan.className = "win-commandicon"; - this._iconSpan.tabIndex = -1; - this._element.appendChild(this._iconSpan); - this._imageSpan = _Global.document.createElement("span"); - this._imageSpan.setAttribute("aria-hidden", "true"); - this._imageSpan.className = "win-commandimage"; - this._imageSpan.tabIndex = -1; - this._iconSpan.appendChild(this._imageSpan); - this._labelSpan = _Global.document.createElement("span"); - this._labelSpan.setAttribute("aria-hidden", "true"); - this._labelSpan.className = "win-label"; - this._labelSpan.tabIndex = -1; - this._element.appendChild(this._labelSpan); - // 'win-global' or 'win-selection' are added later by caller. - // Label and icon are added later by caller. - - // Attach a tooltip - Note: we're going to stomp on it's setControl so we don't have to make another DOM element to hang it off of. - // This private _tooltipControl attribute is used by other pieces, changing the name could break them. - this._tooltipControl = new Tooltip.Tooltip(this._element); - var that = this; - this._tooltipControl.addEventListener("beforeopen", function () { - if (that._hideIfFullSize && !_Overlay._Overlay._getParentControlUsingClassName(that._element.parentElement, _Constants.reducedClass)) { - that._tooltipControl.close(); - } - }, false); - }, - - _setSection: function AppBarCommand_setSection(section) { - if (!section) { - section = _Constants.sectionPrimary; - } - - // _Constants.sectionSelection and _Constants.sectionGlobal are deprecated, so we will continue - // adding/removing its corresponding CSS class for app compat. - // _Constants.sectionPrimary and _Constants.sectionSecondary no longer apply CSS classes to the - // commands. - - if (this._section) { - // Remove the old section class - if (this._section === _Constants.sectionGlobal) { - _ElementUtilities.removeClass(this._element, _Constants.appBarCommandGlobalClass); - } else if (this.section === _Constants.sectionSelection) { - _ElementUtilities.removeClass(this._element, _Constants.appBarCommandSelectionClass); - } - } - // Add the new section class - this._section = section; - if (section === _Constants.sectionGlobal) { - _ElementUtilities.addClass(this._element, _Constants.appBarCommandGlobalClass); - } else if (section === _Constants.sectionSelection) { - _ElementUtilities.addClass(this._element, _Constants.appBarCommandSelectionClass); - } - }, - - _updateTabStop: function AppBarCommand_updateTabStop() { - // Whenever the firstElementFocus or lastElementFocus properties are set for content type AppBarCommands, - // the containing command element is no longer a tabstop. - - if (this._firstElementFocus || this._lastElementFocus) { - this.element.tabIndex = -1; - } else { - this.element.tabIndex = 0; - } - }, - - _isFocusable: function AppBarCommand_isFocusable() { - return (!this.hidden && this._type !== _Constants.typeSeparator && !this.element.disabled && - (this.firstElementFocus.tabIndex >= 0 || this.lastElementFocus.tabIndex >= 0)); - }, - - _sendEvent: function AppBarCommand_sendEvent(eventName, detail) { - if (this._disposed) { - return; - } - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(eventName, true, true, (detail || {})); - return this._element.dispatchEvent(event); - }, - }); - - - // The list of AppBarCommand properties that we care about firing an event - // for, whenever they are changed after initial construction. - var ObservablePropertyWhiteList = [ - "label", - "disabled", - "flyout", - "extraClass", - "selected", - "onclick", - "hidden", - ]; - - function makeObservable(command, propertyName) { - // Make a pre-existing AppBarCommand property observable by firing the "_commandpropertymutated" - // event whenever its value changes. - - // Preserve initial value in JS closure variable - var _value = command[propertyName]; - - // Preserve original getter/setter if they exist, else use inline proxy functions. - var proto = command.constructor.prototype; - var originalDesc = getPropertyDescriptor(proto, propertyName) || {}; - var getter = originalDesc.get.bind(command) || function getterProxy() { - return _value; - }; - var setter = originalDesc.set.bind(command) || function setterProxy(value) { - _value = value; - }; - - // Define new observable Get/Set for propertyName on the command instance - Object.defineProperty(command, propertyName, { - get: function observable_get() { - return getter(); - }, - set: function observable_set(value) { - - var oldValue = getter(); - - // Process value through the original setter & getter before deciding to send an event. - setter(value); - var newValue = getter(); - if (!this._disposed && oldValue !== value && oldValue !== newValue && !command._disposed) { - - command._propertyMutations.dispatchEvent( - _Constants.commandPropertyMutated, - { - command: command, - propertyName: propertyName, - oldValue: oldValue, - newValue: newValue, - }); - } - } - }); - } - - function getPropertyDescriptor(obj, propertyName) { - // Returns a matching property descriptor, or null, - // if no matching descriptor is found. - var desc = null; - while (obj && !desc) { - desc = Object.getOwnPropertyDescriptor(obj, propertyName); - obj = Object.getPrototypeOf(obj); - // Walk obj's prototype chain until we find a match. - } - return desc; - } - - return AppBarCommand; - }) - }); - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - Command: _Base.Namespace._lazy(function () { return exports.AppBarCommand; }) - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -// Menu Command -/// appbar,appbars,Flyout,Flyouts,onclick,Statics -define('WinJS/Controls/Menu/_Command',[ - 'exports', - '../../Core/_Global', - '../../Core/_Base', - '../../Core/_ErrorFromName', - '../../Core/_Resources', - '../../Promise', - '../../Utilities/_Control', - '../../Utilities/_ElementUtilities', - '../_LegacyAppBar/_Constants', - '../Flyout/_Overlay' -], function menuCommandInit(exports, _Global, _Base, _ErrorFromName, _Resources, Promise, _Control, _ElementUtilities, _Constants, _Overlay) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// - /// Represents a command to be displayed in a Menu. MenuCommand objects provide button, toggle button, flyout button, - /// or separator functionality for Menu controls. - /// - /// - /// - /// - /// - /// ]]> - /// The MenuCommand control itself - /// - /// - MenuCommand: _Base.Namespace._lazy(function () { - - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/menuCommandAriaLabel").value; }, - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get badClick() { return "Invalid argument: The onclick property for an {0} must be a function"; }, - get badHrElement() { return "Invalid argument: For a separator, the element must be null or an hr element"; }, - get badButtonElement() { return "Invalid argument: For a button, toggle, or flyout command, the element must be null or a button element"; } - }; - - var MenuCommand = _Base.Class.define(function MenuCommand_ctor(element, options) { - /// - /// - /// Creates a new MenuCommand object. - /// - /// - /// The DOM element that will host the control. - /// - /// - /// The set of properties and values to apply to the new MenuCommand. - /// - /// - /// A MenuCommand control. - /// - /// - /// - - // Check to make sure we weren't duplicated - if (element && element.winControl) { - throw new _ErrorFromName("WinJS.UI.MenuCommand.DuplicateConstruction", strings.duplicateConstruction); - } - - this._disposed = false; - - // Don't blow up if they didn't pass options - if (!options) { - options = {}; - } - - // Need a type before we can create our element - if (!options.type) { - this._type = _Constants.typeButton; - } - - // Go ahead and create it, separator types look different than buttons - // Don't forget to use passed in element if one was provided. - this._element = element; - if (options.type === _Constants.typeSeparator) { - this._createSeparator(); - } else { - // This will also set the icon & label - this._createButton(); - } - _ElementUtilities.addClass(this._element, "win-disposable"); - - // Remember ourselves - this._element.winControl = this; - - // Attach our css class - _ElementUtilities.addClass(this._element, _Constants.menuCommandClass); - - if (!options.selected && options.type === _Constants.typeToggle) { - // Make sure toggle's have selected false for CSS - this.selected = false; - } - - if (options.onclick) { - this.onclick = options.onclick; - } - options.onclick = this._handleClick.bind(this); - - _Control.setOptions(this, options); - - // Set our options - if (this._type !== _Constants.typeSeparator) { - // Make sure we have an ARIA role - var role = this._element.getAttribute("role"); - if (role === null || role === "" || role === undefined) { - role = "menuitem"; - if (this._type === _Constants.typeToggle) { - role = "menuitemcheckbox"; - } - this._element.setAttribute("role", role); - if (this._type === _Constants.typeFlyout) { - this._element.setAttribute("aria-haspopup", true); - } - } - var label = this._element.getAttribute("aria-label"); - if (label === null || label === "" || label === undefined) { - this._element.setAttribute("aria-label", strings.ariaLabel); - } - } - - }, { - /// - /// Gets the ID of the MenuCommand. - /// - /// - id: { - get: function () { - return this._element.id; - }, - set: function (value) { - // we allow setting first time only. otherwise we ignore it. - if (!this._element.id) { - this._element.id = value; - } - } - }, - - /// - /// Gets the type of the MenuCommand. Possible values are "button", "toggle", "flyout", or "separator". - /// - /// - type: { - get: function () { - return this._type; - }, - set: function (value) { - // we allow setting first time only. otherwise we ignore it. - if (!this._type) { - if (value !== _Constants.typeButton && value !== _Constants.typeFlyout && value !== _Constants.typeToggle && value !== _Constants.typeSeparator) { - value = _Constants.typeButton; - } - - this._type = value; - - if (value === _Constants.typeButton) { - _ElementUtilities.addClass(this.element, _Constants.menuCommandButtonClass); - } else if (value === _Constants.typeFlyout) { - _ElementUtilities.addClass(this.element, _Constants.menuCommandFlyoutClass); - this.element.addEventListener("keydown", this._handleKeyDown.bind(this), false); - } else if (value === _Constants.typeSeparator) { - _ElementUtilities.addClass(this.element, _Constants.menuCommandSeparatorClass); - } else if (value === _Constants.typeToggle) { - _ElementUtilities.addClass(this.element, _Constants.menuCommandToggleClass); - } - } - } - }, - - /// - /// The label of the MenuCommand - /// - /// - label: { - get: function () { - return this._label; - }, - set: function (value) { - this._label = value || ""; - if (this._labelSpan) { - this._labelSpan.textContent = this.label; - } - - // Update aria-label - this._element.setAttribute("aria-label", this.label); - } - }, - - /// - /// Gets or sets the function to invoke when the command is clicked. - /// - /// - onclick: { - get: function () { - return this._onclick; - }, - set: function (value) { - if (value && typeof value !== "function") { - throw new _ErrorFromName("WinJS.UI.MenuCommand.BadClick", _Resources._formatString(strings.badClick, "MenuCommand")); - } - this._onclick = value; - } - }, - - /// - /// For flyout type MenuCommands, this property returns the WinJS.UI.Flyout that this command invokes. When setting this property, you can set - /// it to the string ID of the Flyout, the DOM object that hosts the Flyout, or the Flyout object itself. - /// - /// - flyout: { - get: function () { - // Resolve it to the flyout - var flyout = this._flyout; - if (typeof flyout === "string") { - flyout = _Global.document.getElementById(flyout); - } - // If it doesn't have a .element, then we need to getControl on it - if (flyout && !flyout.element) { - flyout = flyout.winControl; - } - - return flyout; - }, - set: function (value) { - - // Need to update aria-owns with the new ID. - var id = value; - if (id && typeof id !== "string") { - // Our controls have .element properties - if (id.element) { - id = id.element; - } - // Hope it's a DOM element, get ID from DOM element - if (id) { - if (id.id) { - id = id.id; - } else { - // No id, have to fake one - id.id = _ElementUtilities._uniqueID(id); - id = id.id; - } - } - } - if (typeof id === "string") { - this._element.setAttribute("aria-owns", id); - } - - if (this._flyout !== value) { - MenuCommand._deactivateFlyoutCommand(this); - } - - // Remember it - this._flyout = value; - } - }, - - /// - /// Gets or sets the selected state of a toggle button. This property is true if the toggle button is selected; otherwise, it's false. - /// - /// - selected: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return this._element.getAttribute("aria-checked") === "true"; - }, - set: function (value) { - this._element.setAttribute("aria-checked", !!value); - } - }, - - /// - element: { - get: function () { - return this._element; - } - }, - - /// - /// Gets or sets a value that indicates whether the MenuCommand is disabled. This value is true if the MenuCommand is disabled; otherwise, false. - /// - /// - disabled: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return !!this._element.disabled; - }, - set: function (value) { - value = !!value; - if (value && this.type === _Constants.typeFlyout) { - MenuCommand._deactivateFlyoutCommand(this); - } - this._element.disabled = value; - } - }, - - /// - hidden: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return this._element.style.visibility === "hidden"; - }, - set: function (value) { - var menuControl = _Overlay._Overlay._getParentControlUsingClassName(this._element, _Constants.menuClass); - if (menuControl && !menuControl.hidden) { - throw new _ErrorFromName("WinJS.UI.MenuCommand.CannotChangeHiddenProperty", _Resources._formatString(_Overlay._Overlay.commonstrings.cannotChangeHiddenProperty, "Menu")); - } - - var style = this._element.style; - if (value) { - if (this.type === _Constants.typeFlyout) { - MenuCommand._deactivateFlyoutCommand(this); - } - style.visibility = "hidden"; - style.display = "none"; - } else { - style.visibility = ""; - style.display = "block"; - } - } - }, - - /// - /// Gets or sets the extra CSS class that is applied to the host DOM element. - /// - /// - extraClass: { - get: function () { - return this._extraClass; - }, - set: function (value) { - if (this._extraClass) { - _ElementUtilities.removeClass(this._element, this._extraClass); - } - this._extraClass = value; - _ElementUtilities.addClass(this._element, this._extraClass); - } - }, - - - dispose: function () { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - }, - - addEventListener: function (type, listener, useCapture) { - /// - /// - /// Registers an event handler for the specified event. - /// - /// The name of the event to register. - /// The function that handles the event. - /// - /// Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - /// - /// - /// - return this._element.addEventListener(type, listener, useCapture); - }, - - removeEventListener: function (type, listener, useCapture) { - /// - /// - /// Removes the specified event handler that the addEventListener method registered. - /// - /// The name of the event to remove. - /// The event handler function to remove. - /// - /// Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - /// - /// - /// - return this._element.removeEventListener(type, listener, useCapture); - }, - - // Private properties - _createSeparator: function MenuCommand_createSeparator() { - // Make sure there's an input element - if (!this._element) { - this._element = _Global.document.createElement("hr"); - } else { - // Verify the input was an hr - if (this._element.tagName !== "HR") { - throw new _ErrorFromName("WinJS.UI.MenuCommand.BadHrElement", strings.badHrElement); - } - } - }, - - _createButton: function MenuCommand_createButton() { - // Make sure there's an element - if (!this._element) { - this._element = _Global.document.createElement("button"); - } else { - // Verify the input was a button - if (this._element.tagName !== "BUTTON") { - throw new _ErrorFromName("WinJS.UI.MenuCommand.BadButtonElement", strings.badButtonElement); - } - } - - // Create our inner HTML. We will set aria values on the button itself further down in the constructor. - this._element.innerHTML = - '
' + - '' + - '' + - '' + - '
'; - this._element.type = "button"; - - // The purpose of menuCommandLiner is to lay out the MenuCommand's children in a flexbox. Ideally, this flexbox would - // be on MenuCommand.element. However, firefox lays out buttons with display:flex differently. - // Firefox bug 1014285 (Button with display:inline-flex doesn't layout properly) - // https://bugzilla.mozilla.org/show_bug.cgi?id=1014285 - this._menuCommandLiner = this._element.firstElementChild; - this._toggleSpan = this._menuCommandLiner.firstElementChild; - this._labelSpan = this._toggleSpan.nextElementSibling; - this._flyoutSpan = this._labelSpan.nextElementSibling; - - }, - _sendEvent: function MenuCommand_sendEvent(eventName, detail) { - if (!this._disposed) { - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(eventName, true, true, (detail || {})); - this._element.dispatchEvent(event); - } - }, - - _invoke: function MenuCommand_invoke(event) { - if (!this.hidden && !this.disabled && !this._disposed) { - if (this._type === _Constants.typeToggle) { - this.selected = !this.selected; - } else if (this._type === _Constants.typeFlyout) { - MenuCommand._activateFlyoutCommand(this); - } - - if (event && event.type === "click" && this.onclick) { - this.onclick(event); - } - - // Bubble private 'invoked' event to Menu - this._sendEvent(_Constants._menuCommandInvokedEvent, { command: this }); - } - }, - - _handleClick: function MenuCommand_handleClick(event) { - this._invoke(event); - }, - - _handleKeyDown: function MenuCommand_handleKeyDown(event) { - var Key = _ElementUtilities.Key, - rtl = _Global.getComputedStyle(this.element).direction === "rtl", - rightKey = rtl ? Key.leftArrow : Key.rightArrow; - - if (event.keyCode === rightKey && this.type === _Constants.typeFlyout) { - this._invoke(event); - - // Prevent the page from scrolling - event.preventDefault(); - } - }, - }, { - // Statics - _activateFlyoutCommand: function MenuCommand_activateFlyoutCommand(menuCommand) { - // Activates the associated Flyout command and returns a promise once complete. - // A command is considered to be activated once the proper CSS class has been applied and its associated flyout has finished showing. - return new Promise(function (c, e) { - menuCommand = menuCommand.winControl || menuCommand; - var subFlyout = menuCommand.flyout; - // Flyout may not have processAll'd, so this may be a DOM object - if (subFlyout && subFlyout.hidden && subFlyout.show) { - _ElementUtilities.addClass(menuCommand.element, _Constants.menuCommandFlyoutActivatedClass); - - // Remove activation class from the command if the flyout is ever hidden. - subFlyout.addEventListener("beforehide", function beforeHide() { - subFlyout.removeEventListener("beforehide", beforeHide, false); - _ElementUtilities.removeClass(menuCommand.element, _Constants.menuCommandFlyoutActivatedClass); - }, false); - - subFlyout.addEventListener("aftershow", function afterShow() { - subFlyout.removeEventListener("aftershow", afterShow, false); - // We are considered activated once we start showing the flyout. - c(); - }, false); - - subFlyout.show(menuCommand, "_cascade"); - } else { - // Could not change command to activated state. - e(); - } - }); - }, - - _deactivateFlyoutCommand: function MenuCommand_deactivateFlyoutCommand(menuCommand) { - // Deactivates the associated Flyout command and returns a promise once complete. - // A command is considered to be deactivated once the proper CSS class has been applied and its associated flyout has finished hiding. - return new Promise(function (c) { - menuCommand = menuCommand.winControl || menuCommand; - _ElementUtilities.removeClass(menuCommand.element, _Constants.menuCommandFlyoutActivatedClass); - - var subFlyout = menuCommand.flyout; - // Flyout may not have processAll'd, so this may be a DOM object - if (subFlyout && !subFlyout.hidden && subFlyout.hide) { - - subFlyout.addEventListener("afterhide", function afterHide() { - subFlyout.removeEventListener("afterhide", afterHide, false); - c(); - }, false); - - subFlyout.hide(); - } else { - // subFlyout does not need to be hidden. - c(); - } - }); - }, - }); - return MenuCommand; - }) - }); - -}); - - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -var __extends = this.__extends || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -define('WinJS/Controls/CommandingSurface/_MenuCommand',["require", "exports", "../Menu/_Command"], function (require, exports, _MenuCommandBase) { - var _MenuCommand = (function (_super) { - __extends(_MenuCommand, _super); - function _MenuCommand(element, options) { - if (options && options.beforeInvoke) { - this._beforeInvoke = options.beforeInvoke; - } - _super.call(this, element, options); - } - _MenuCommand.prototype._invoke = function (event) { - this._beforeInvoke && this._beforeInvoke(event); - _super.prototype._invoke.call(this, event); - }; - return _MenuCommand; - })(_MenuCommandBase.MenuCommand); - exports._MenuCommand = _MenuCommand; -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Utilities/_OpenCloseMachine',["require", "exports", '../Core/_Global', '../Promise', '../_Signal'], function (require, exports, _Global, Promise, _Signal) { - "use strict"; - // This module provides a state machine which is designed to be used by controls which need to - // open, close, and fire related events (e.g. beforeopen, afterclose). The state machine handles - // many edge cases. For example, what happens if: - // - open is called when we're already opened? - // - close is called while we're in the middle of opening? - // - dispose is called while we're in the middle of firing beforeopen? - // The state machine takes care of all of these edge cases so that the control doesn't have to. - // The control is responible for knowing how to play its open/close animations and update its DOM. - // The state machine is responsible for ensuring that these things happen at the appropriate times. - // This module is broken up into 3 major pieces: - // - OpenCloseMachine: Controls should instantiate one of these. The machine keeps track of the - // current state and has methods for forwarding calls to the current state. - // - IOpenCloseControl: Controls must provide an object which implements this interface. The - // interface gives the machine hooks for invoking the control's open and close animations. - // - States: The various states (e.g. Closed, Opened, Opening) that the machine can be in. Each - // implements IOpenCloseState. - // Example usage: - // class MyControl { - // element: HTMLElement; - // private _machine: OpenCloseMachine; - // - // constructor(element?: HTMLElement, options: any = {}) { - // this.element = element || document.createElement("div"); - // - // // Create the machine. - // this._machine = new OpenCloseMachine({ - // eventElement: this.element, - // onOpen: (): Promise => { - // // Do the work to render the contol in its opened state with an animation. - // // Return the animation promise. - // }, - // onClose: (): Promise => { - // // Do the work to render the contol in its closed state with an animation. - // // Return the animation promise. - // }, - // onUpdateDom() { - // // Do the work to render the internal state of the control to the DOM. If a - // // control restricts all its DOM modifications to onUpdateDom, the state machine - // // can guarantee that the control won't modify its DOM while it is animating. - // }, - // onUpdateDomWithIsOpened: (isOpened: boolean ) => { - // // Do the same work as onUpdateDom but ensure that the DOM is rendered with either - // // the opened or closed visual as dictacted by isOpened. The control should have some - // // internal state to track whether it is currently opened or closed. Treat this as a - // // cue to mutate that internal state to reflect the value of isOpened. - // }, - // }); - // - // // Initialize the control. During this time, the machine will not ask the control to - // // play any animations or update its DOM. - // this.opened = true; - // _Control.setOptions(this, options); - // - // // Tell the machine the control is initialized. After this, the machine will start asking - // // the control to play animations and update its DOM as appropriate. - // this._machine.exitInit(); - // } - // - // get opened() { - // return this._machine.opened; - // } - // set opened(value: boolean) { - // this._machine.opened = value; - // } - // open() { - // this._machine.open(); - // } - // close() { - // this._machine.close(); - // } - // forceLayout() { - // this._machine.updateDom(); - // } - // dispose() { - // this._machine.dispose(); - // } - // } - var EventNames = { - beforeOpen: "beforeopen", - afterOpen: "afteropen", - beforeClose: "beforeclose", - afterClose: "afterclose", - // Private events - // Indicates that the OpenCloseMachine has settled either into the Opened state - // or Closed state. This is more comprehensive than the "afteropen" and "afterclose" - // events because it fires even if the machine has reached the state due to: - // - Exiting the Init state - // - The beforeopen/beforeclose events being canceled - _openCloseStateSettled: "_openCloseStateSettled" - }; - // - // OpenCloseMachine - // - var OpenCloseMachine = (function () { - // - // Methods called by the control - // - // When the machine is created, it sits in the Init state. When in the Init state, calls to - // updateDom will be postponed until the machine exits the Init state. Consequently, while in - // this state, the control can feel free to call updateDom as many times as it wants without - // worrying about it being expensive due to updating the DOM many times. The control should call - // *exitInit* to move the machine out of the Init state. - function OpenCloseMachine(args) { - this._control = args; - this._initializedSignal = new _Signal(); - this._disposed = false; - this._setState(States.Init); - } - // Moves the machine out of the Init state and into the Opened or Closed state depending on whether - // open or close was called more recently. - OpenCloseMachine.prototype.exitInit = function () { - this._initializedSignal.complete(); - }; - // These method calls are forwarded to the current state. - OpenCloseMachine.prototype.updateDom = function () { - this._state.updateDom(); - }; - OpenCloseMachine.prototype.open = function () { - this._state.open(); - }; - OpenCloseMachine.prototype.close = function () { - this._state.close(); - }; - Object.defineProperty(OpenCloseMachine.prototype, "opened", { - get: function () { - return this._state.opened; - }, - set: function (value) { - if (value) { - this.open(); - } - else { - this.close(); - } - }, - enumerable: true, - configurable: true - }); - // Puts the machine into the Disposed state. - OpenCloseMachine.prototype.dispose = function () { - this._setState(States.Disposed); - this._disposed = true; - this._control = null; - }; - // - // Methods called by states - // - OpenCloseMachine.prototype._setState = function (NewState, arg0) { - if (!this._disposed) { - this._state && this._state.exit(); - this._state = new NewState(); - this._state.machine = this; - this._state.enter(arg0); - } - }; - // Triggers arbitrary app code - OpenCloseMachine.prototype._fireEvent = function (eventName, options) { - options = options || {}; - var detail = options.detail || null; - var cancelable = !!options.cancelable; - var eventObject = _Global.document.createEvent("CustomEvent"); - eventObject.initCustomEvent(eventName, true, cancelable, detail); - return this._control.eventElement.dispatchEvent(eventObject); - }; - // Triggers arbitrary app code - OpenCloseMachine.prototype._fireBeforeOpen = function () { - return this._fireEvent(EventNames.beforeOpen, { - cancelable: true - }); - }; - // Triggers arbitrary app code - OpenCloseMachine.prototype._fireBeforeClose = function () { - return this._fireEvent(EventNames.beforeClose, { - cancelable: true - }); - }; - return OpenCloseMachine; - })(); - exports.OpenCloseMachine = OpenCloseMachine; - // - // States (each implements IOpenCloseState) - // - // WinJS animation promises always complete successfully. This - // helper allows an animation promise to complete in the canceled state - // so that the success handler can be skipped when the animation is - // interrupted. - function cancelablePromise(animationPromise) { - return Promise._cancelBlocker(animationPromise, function () { - animationPromise.cancel(); - }); - } - // Noop function, used in the various states to indicate that they don't support a given - // message. Named with the somewhat cute name '_' because it reads really well in the states. - function _() { - } - // Implementing the control as a state machine helps us correctly handle: - // - re-entrancy while firing events - // - calls into the control during asynchronous operations (e.g. animations) - // - // Many of the states do their "enter" work within a promise chain. The idea is that if - // the state is interrupted and exits, the rest of its work can be skipped by canceling - // the promise chain. - // An interesting detail is that anytime the state may trigger app code (e.g. due to - // firing an event), the current promise must end and a new promise must be chained off of it. - // This is necessary because the app code may interact with the control and cause it to - // change states. If we didn't create a new promise, then the very next line of code that runs - // after triggering app code may not be valid because the state may have exited. Starting a - // new promise after each triggering of app code prevents us from having to worry about this - // problem. In this configuration, when a promise's success handler runs, it guarantees that - // the state hasn't exited. - // For similar reasons, each of the promise chains created in "enter" starts off with a _Signal - // which is completed at the end of the "enter" function (this boilerplate is abstracted away by - // the "interruptible" function). The reason is that we don't want any of the code in "enter" - // to run until the promise chain has been stored in a variable. If we didn't do this (e.g. instead, - // started the promise chain with Promise.wrap()), then the "enter" code could trigger the "exit" - // function (via app code) before the promise chain had been stored in a variable. Under these - // circumstances, the promise chain would be uncancelable and so the "enter" work would be - // unskippable. This wouldn't be good when we needed the state to exit early. - // These two functions manage interruptible work promises (one creates them the other cancels - // them). They communicate with each other thru the _interruptibleWorkPromises property which - // "interruptible" creates on your object. - function interruptible(object, workFn) { - object["_interruptibleWorkPromises"] = object["_interruptibleWorkPromises"] || []; - var workStoredSignal = new _Signal(); - object["_interruptibleWorkPromises"].push(workFn(workStoredSignal.promise)); - workStoredSignal.complete(); - } - function cancelInterruptibles() { - (this["_interruptibleWorkPromises"] || []).forEach(function (workPromise) { - workPromise.cancel(); - }); - } - // Transitions: - // When created, the state machine will take one of the following initialization - // transitions depending on how the machines's APIs have been used by the time - // exitInit() is called on it: - // Init -> Closed - // Init -> Opened - // Following that, the life of the machine will be dominated by the following - // sequences of transitions. In geneneral, these sequences are uninterruptible. - // Closed -> BeforeOpen -> Closed (when preventDefault is called on beforeopen event) - // Closed -> BeforeOpen -> Opening -> Opened - // Opened -> BeforeClose -> Opened (when preventDefault is called on beforeclose event) - // Opened -> BeforeClose -> Closing -> Closed - // However, any state can be interrupted to go to the Disposed state: - // * -> Disposed - var States; - (function (States) { - function updateDomImpl() { - this.machine._control.onUpdateDom(); - } - // Initial state. Gives the control the opportunity to initialize itself without - // triggering any animations or DOM modifications. When done, the control should - // call *exitInit* to move the machine to the next state. - var Init = (function () { - function Init() { - this.name = "Init"; - this.exit = cancelInterruptibles; - this.updateDom = _; // Postponed until immediately before we switch to another state - } - Init.prototype.enter = function () { - var _this = this; - interruptible(this, function (ready) { - return ready.then(function () { - return _this.machine._initializedSignal.promise; - }).then(function () { - _this.machine._control.onUpdateDomWithIsOpened(_this._opened); - _this.machine._setState(_this._opened ? Opened : Closed); - }); - }); - }; - Object.defineProperty(Init.prototype, "opened", { - get: function () { - return this._opened; - }, - enumerable: true, - configurable: true - }); - Init.prototype.open = function () { - this._opened = true; - }; - Init.prototype.close = function () { - this._opened = false; - }; - return Init; - })(); - States.Init = Init; - // A rest state. The control is closed and is waiting for the app to call open. - var Closed = (function () { - function Closed() { - this.name = "Closed"; - this.exit = _; - this.opened = false; - this.close = _; - this.updateDom = updateDomImpl; - } - Closed.prototype.enter = function (args) { - args = args || {}; - if (args.openIsPending) { - this.open(); - } - this.machine._fireEvent(EventNames._openCloseStateSettled); - }; - Closed.prototype.open = function () { - this.machine._setState(BeforeOpen); - }; - return Closed; - })(); - // An event state. The control fires the beforeopen event. - var BeforeOpen = (function () { - function BeforeOpen() { - this.name = "BeforeOpen"; - this.exit = cancelInterruptibles; - this.opened = false; - this.open = _; - this.close = _; - this.updateDom = updateDomImpl; - } - BeforeOpen.prototype.enter = function () { - var _this = this; - interruptible(this, function (ready) { - return ready.then(function () { - return _this.machine._fireBeforeOpen(); // Give opportunity for chain to be canceled when triggering app code - }).then(function (shouldOpen) { - if (shouldOpen) { - _this.machine._setState(Opening); - } - else { - _this.machine._setState(Closed); - } - }); - }); - }; - return BeforeOpen; - })(); - // An animation/event state. The control plays its open animation and fires afteropen. - var Opening = (function () { - function Opening() { - this.name = "Opening"; - this.exit = cancelInterruptibles; - this.updateDom = _; // Postponed until immediately before we switch to another state - } - Opening.prototype.enter = function () { - var _this = this; - interruptible(this, function (ready) { - return ready.then(function () { - _this._closeIsPending = false; - return cancelablePromise(_this.machine._control.onOpen()); - }).then(function () { - _this.machine._fireEvent(EventNames.afterOpen); // Give opportunity for chain to be canceled when triggering app code - }).then(function () { - _this.machine._control.onUpdateDom(); - _this.machine._setState(Opened, { closeIsPending: _this._closeIsPending }); - }); - }); - }; - Object.defineProperty(Opening.prototype, "opened", { - get: function () { - return !this._closeIsPending; - }, - enumerable: true, - configurable: true - }); - Opening.prototype.open = function () { - this._closeIsPending = false; - }; - Opening.prototype.close = function () { - this._closeIsPending = true; - }; - return Opening; - })(); - // A rest state. The control is opened and is waiting for the app to call close. - var Opened = (function () { - function Opened() { - this.name = "Opened"; - this.exit = _; - this.opened = true; - this.open = _; - this.updateDom = updateDomImpl; - } - Opened.prototype.enter = function (args) { - args = args || {}; - if (args.closeIsPending) { - this.close(); - } - this.machine._fireEvent(EventNames._openCloseStateSettled); - }; - Opened.prototype.close = function () { - this.machine._setState(BeforeClose); - }; - return Opened; - })(); - // An event state. The control fires the beforeclose event. - var BeforeClose = (function () { - function BeforeClose() { - this.name = "BeforeClose"; - this.exit = cancelInterruptibles; - this.opened = true; - this.open = _; - this.close = _; - this.updateDom = updateDomImpl; - } - BeforeClose.prototype.enter = function () { - var _this = this; - interruptible(this, function (ready) { - return ready.then(function () { - return _this.machine._fireBeforeClose(); // Give opportunity for chain to be canceled when triggering app code - }).then(function (shouldClose) { - if (shouldClose) { - _this.machine._setState(Closing); - } - else { - _this.machine._setState(Opened); - } - }); - }); - }; - return BeforeClose; - })(); - // An animation/event state. The control plays the close animation and fires the afterclose event. - var Closing = (function () { - function Closing() { - this.name = "Closing"; - this.exit = cancelInterruptibles; - this.updateDom = _; // Postponed until immediately before we switch to another state - } - Closing.prototype.enter = function () { - var _this = this; - interruptible(this, function (ready) { - return ready.then(function () { - _this._openIsPending = false; - return cancelablePromise(_this.machine._control.onClose()); - }).then(function () { - _this.machine._fireEvent(EventNames.afterClose); // Give opportunity for chain to be canceled when triggering app code - }).then(function () { - _this.machine._control.onUpdateDom(); - _this.machine._setState(Closed, { openIsPending: _this._openIsPending }); - }); - }); - }; - Object.defineProperty(Closing.prototype, "opened", { - get: function () { - return this._openIsPending; - }, - enumerable: true, - configurable: true - }); - Closing.prototype.open = function () { - this._openIsPending = true; - }; - Closing.prototype.close = function () { - this._openIsPending = false; - }; - return Closing; - })(); - var Disposed = (function () { - function Disposed() { - this.name = "Disposed"; - this.enter = _; - this.exit = _; - this.opened = false; - this.open = _; - this.close = _; - this.updateDom = _; - } - return Disposed; - })(); - States.Disposed = Disposed; - })(States || (States = {})); -}); - - -define('require-style!less/styles-commandingsurface',[],function(){}); - -define('require-style!less/colors-commandingsurface',[],function(){}); -define('WinJS/Controls/CommandingSurface/_CommandingSurface',["require", "exports", "../../Animations", "../../Core/_Base", "../../Core/_BaseUtils", "../../BindingList", "../../ControlProcessor", "../CommandingSurface/_Constants", "../AppBar/_Command", "../CommandingSurface/_MenuCommand", "../../Utilities/_Control", "../../Utilities/_Dispose", "../../Utilities/_ElementUtilities", "../../Core/_ErrorFromName", '../../Core/_Events', "../../Controls/Flyout", "../../Core/_Global", "../../Utilities/_Hoverable", "../../Utilities/_KeyboardBehavior", '../../Core/_Log', '../../Promise', "../../Core/_Resources", "../../Scheduler", '../../Utilities/_OpenCloseMachine', '../../_Signal', "../../Core/_WriteProfilerMark"], function (require, exports, Animations, _Base, _BaseUtils, BindingList, ControlProcessor, _Constants, _Command, _CommandingSurfaceMenuCommand, _Control, _Dispose, _ElementUtilities, _ErrorFromName, _Events, _Flyout, _Global, _Hoverable, _KeyboardBehavior, _Log, Promise, _Resources, Scheduler, _OpenCloseMachine, _Signal, _WriteProfilerMark) { - require(["require-style!less/styles-commandingsurface"]); - require(["require-style!less/colors-commandingsurface"]); - "use strict"; - var strings = { - get overflowButtonAriaLabel() { - return _Resources._getWinJSString("ui/commandingSurfaceOverflowButtonAriaLabel").value; - }, - get badData() { - return "Invalid argument: The data property must an instance of a WinJS.Binding.List"; - }, - get mustContainCommands() { - return "The commandingSurface can only contain WinJS.UI.Command or WinJS.UI.AppBarCommand controls"; - }, - get duplicateConstruction() { - return "Invalid argument: Controls may only be instantiated one time for each DOM element"; - } - }; - var CommandLayoutPipeline = { - newDataStage: 3, - measuringStage: 2, - layoutStage: 1, - idle: 0, - }; - var OverflowDirection = { - /// The _CommandingSurface expands towards the bottom of the screen when opened and the overflow area renders below the actionarea. - bottom: "bottom", - /// The _CommandingSurface expands towards the top of the screen when opened and the overflow area renders above the actionarea. - top: "top", - }; - var overflowDirectionClassMap = {}; - overflowDirectionClassMap[OverflowDirection.top] = _Constants.ClassNames.overflowTopClass; - overflowDirectionClassMap[OverflowDirection.bottom] = _Constants.ClassNames.overflowBottomClass; - var ClosedDisplayMode = { - /// When the _CommandingSurface is closed, the actionarea is not visible and doesn't take up any space. - none: "none", - /// When the _CommandingSurface is closed, the height of the actionarea is reduced to the minimal height required to display only the actionarea overflowbutton. All other content in the actionarea is not displayed. - minimal: "minimal", - /// When the _CommandingSurface is closed, the height of the actionarea is reduced such that button commands are still visible, but their labels are hidden. - compact: "compact", - /// When the _CommandingSurface is closed, the height of the actionarea is always sized to content and does not change between opened and closed states. - full: "full", - }; - var closedDisplayModeClassMap = {}; - closedDisplayModeClassMap[ClosedDisplayMode.none] = _Constants.ClassNames.noneClass; - closedDisplayModeClassMap[ClosedDisplayMode.minimal] = _Constants.ClassNames.minimalClass; - closedDisplayModeClassMap[ClosedDisplayMode.compact] = _Constants.ClassNames.compactClass; - closedDisplayModeClassMap[ClosedDisplayMode.full] = _Constants.ClassNames.fullClass; - // Versions of add/removeClass that are no ops when called with falsy class names. - function addClass(element, className) { - className && _ElementUtilities.addClass(element, className); - } - function removeClass(element, className) { - className && _ElementUtilities.removeClass(element, className); - } - function diffElements(lhs, rhs) { - // Subtract array rhs from array lhs. - // Returns a new Array containing the subset of elements in lhs that are not also in rhs. - return lhs.filter(function (commandElement) { - return rhs.indexOf(commandElement) < 0; - }); - } - /// Represents an apaptive surface for displaying commands. - var _CommandingSurface = (function () { - function _CommandingSurface(element, options) { - /// Creates a new CommandingSurface control. - /// @param element: The DOM element that will host the control. - /// @param options: The set of properties and values to apply to the new CommandingSurface control. - /// @return: The new CommandingSurface control. - var _this = this; - if (options === void 0) { options = {}; } - this._hoverable = _Hoverable.isHoverable; /* force dependency on hoverable module */ - this._dataChangedEvents = ["itemchanged", "iteminserted", "itemmoved", "itemremoved", "reload"]; - // State private to _updateDomImpl_renderDisplayMode. No other method should make use of it. - // - // Nothing has been rendered yet so these are all initialized to undefined. Because - // they are undefined, the first time _updateDomImpl is called, they will all be - // rendered. - this._updateDomImpl_renderedState = { - closedDisplayMode: undefined, - isOpenedMode: undefined, - overflowDirection: undefined, - overflowAlignmentOffset: undefined, - }; - this._writeProfilerMark("constructor,StartTM"); - // Check to make sure we weren't duplicated - if (element && element["winControl"]) { - throw new _ErrorFromName("WinJS.UI._CommandingSurface.DuplicateConstruction", strings.duplicateConstruction); - } - this._initializeDom(element || _Global.document.createElement("div")); - this._machine = options.openCloseMachine || new _OpenCloseMachine.OpenCloseMachine({ - eventElement: this._dom.root, - onOpen: function () { - _this.synchronousOpen(); - return Promise.wrap(); - }, - onClose: function () { - _this.synchronousClose(); - return Promise.wrap(); - }, - onUpdateDom: function () { - _this.updateDomImpl(); - }, - onUpdateDomWithIsOpened: function (isOpened) { - if (isOpened) { - _this.synchronousOpen(); - } - else { - _this.synchronousClose(); - } - } - }); - // Initialize private state. - this._disposed = false; - this._primaryCommands = []; - this._secondaryCommands = []; - this._refreshBound = this._refresh.bind(this); - this._resizeHandlerBound = this._resizeHandler.bind(this); - this._winKeyboard = new _KeyboardBehavior._WinKeyboard(this._dom.root); - this._refreshPending = false; - this._rtl = false; - this._initializedSignal = new _Signal(); - this._nextLayoutStage = CommandLayoutPipeline.idle; - this._isOpenedMode = _Constants.defaultOpened; - this._menuCommandProjections = []; - // Initialize public properties. - this.overflowDirection = _Constants.defaultOverflowDirection; - this.closedDisplayMode = _Constants.defaultClosedDisplayMode; - this.opened = this._isOpenedMode; - if (!options.data) { - // Shallow copy object so we can modify it. - options = _BaseUtils._shallowCopy(options); - // Set default data - options.data = options.data || this._getDataFromDOMElements(); - } - _Control.setOptions(this, options); - // Event handlers - _ElementUtilities._resizeNotifier.subscribe(this._dom.root, this._resizeHandlerBound); - this._dom.root.addEventListener('keydown', this._keyDownHandler.bind(this)); - // Exit the Init state. - _ElementUtilities._inDom(this._dom.root).then(function () { - _this._rtl = _Global.getComputedStyle(_this._dom.root).direction === 'rtl'; - if (!options.openCloseMachine) { - // We should only call exitInit on the machine when we own the machine. - _this._machine.exitInit(); - } - _this._initializedSignal.complete(); - _this._writeProfilerMark("constructor,StopTM"); - }); - } - Object.defineProperty(_CommandingSurface.prototype, "element", { - /// Gets the DOM element that hosts the CommandingSurface. - get: function () { - return this._dom.root; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(_CommandingSurface.prototype, "data", { - /// Gets or sets the Binding List of WinJS.UI.Command for the CommandingSurface. - get: function () { - return this._data; - }, - set: function (value) { - this._writeProfilerMark("set_data,info"); - if (value !== this.data) { - if (!(value instanceof BindingList.List)) { - throw new _ErrorFromName("WinJS.UI._CommandingSurface.BadData", strings.badData); - } - if (this._data) { - this._removeDataListeners(); - } - this._data = value; - this._addDataListeners(); - this._dataUpdated(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(_CommandingSurface.prototype, "closedDisplayMode", { - /// Gets or sets the closedDisplayMode for the CommandingSurface. Values are "none", "minimal", "compact", and "full". - get: function () { - return this._closedDisplayMode; - }, - set: function (value) { - this._writeProfilerMark("set_closedDisplayMode,info"); - var isChangingState = (value !== this._closedDisplayMode); - if (ClosedDisplayMode[value] && isChangingState) { - this._closedDisplayMode = value; - this._machine.updateDom(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(_CommandingSurface.prototype, "overflowDirection", { - /// Gets or sets which direction the commandingSurface overflows when opened. Values are "top" and "bottom" for. - get: function () { - return this._overflowDirection; - }, - set: function (value) { - var isChangingState = (value !== this._overflowDirection); - if (OverflowDirection[value] && isChangingState) { - this._overflowDirection = value; - this._machine.updateDom(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(_CommandingSurface.prototype, "opened", { - /// Gets or sets whether the _CommandingSurface is currently opened. - get: function () { - return this._machine.opened; - }, - set: function (value) { - this._machine.opened = value; - }, - enumerable: true, - configurable: true - }); - _CommandingSurface.prototype.open = function () { - /// Opens the _CommandingSurface's actionarea and overflowarea - this._machine.open(); - }; - _CommandingSurface.prototype.close = function () { - /// Closes the _CommandingSurface's actionarea and overflowarea - this._machine.close(); - }; - _CommandingSurface.prototype.dispose = function () { - /// Disposes this CommandingSurface. - if (this._disposed) { - return; - } - this._disposed = true; - this._machine.dispose(); - _ElementUtilities._resizeNotifier.unsubscribe(this._dom.root, this._resizeHandlerBound); - if (this._contentFlyout) { - this._contentFlyout.dispose(); - this._contentFlyout.element.parentNode.removeChild(this._contentFlyout.element); - } - _Dispose.disposeSubTree(this._dom.root); - }; - _CommandingSurface.prototype.forceLayout = function () { - /// Forces the CommandingSurface to update its layout. Use this function when the window did not change - /// size, but the container of the CommandingSurface changed size. - this._meaurementsDirty(); - this._machine.updateDom(); - }; - _CommandingSurface.prototype.getBoundingRects = function () { - return { - commandingSurface: this._dom.root.getBoundingClientRect(), - overflowArea: this._dom.overflowArea.getBoundingClientRect(), - }; - }; - _CommandingSurface.prototype.getCommandById = function (id) { - if (this._data) { - for (var i = 0, len = this._data.length; i < len; i++) { - var command = this._data.getAt(i); - if (command.id === id) { - return command; - } - } - } - return null; - }; - _CommandingSurface.prototype.showOnlyCommands = function (commands) { - if (this._data) { - for (var i = 0, len = this._data.length; i < len; i++) { - this._data.getAt(i).hidden = true; - } - for (var i = 0, len = commands.length; i < len; i++) { - // The array passed to showOnlyCommands can contain either command ids, or the commands themselves. - var command = (typeof commands[i] === "string" ? this.getCommandById(commands[i]) : commands[i]); - if (command) { - command.hidden = false; - } - } - } - }; - _CommandingSurface.prototype.deferredDomUpate = function () { - // Notify the machine that an update has been requested. - this._machine.updateDom(); - }; - _CommandingSurface.prototype.createOpenAnimation = function (closedHeight) { - // createOpenAnimation should only be called when the commanding surface is in a closed state. The control using the commanding surface is expected - // to call createOpenAnimation() before it opens the surface, then open the commanding surface, then call .execute() to start the animation. - // This function is overridden by our unit tests. - if (_Log.log) { - this._updateDomImpl_renderedState.isOpenedMode && _Log.log("The CommandingSurface should only attempt to create an open animation when it's not already opened"); - } - var that = this; - return { - execute: function () { - var boundingRects = that.getBoundingRects(); - // The overflowAreaContainer has no size by default. Measure the overflowArea's size and apply it to the overflowAreaContainer before animating - that._dom.overflowAreaContainer.style.width = boundingRects.overflowArea.width + "px"; - that._dom.overflowAreaContainer.style.height = boundingRects.overflowArea.height + "px"; - return Animations._commandingSurfaceOpenAnimation({ - actionAreaClipper: that._dom.actionAreaContainer, - actionArea: that._dom.actionArea, - overflowAreaClipper: that._dom.overflowAreaContainer, - overflowArea: that._dom.overflowArea, - oldHeight: closedHeight, - newHeight: boundingRects.commandingSurface.height, - overflowAreaHeight: boundingRects.overflowArea.height, - menuPositionedAbove: (that.overflowDirection === OverflowDirection.top), - }).then(function () { - that._clearAnimation(); - }); - } - }; - }; - _CommandingSurface.prototype.createCloseAnimation = function (closedHeight) { - // createCloseAnimation should only be called when the commanding surface is in an opened state. The control using the commanding surface is expected - // to call createCloseAnimation() before it closes the surface, then call execute() to let the animation run. Once the animation finishes, the control - // should close the commanding surface. - // This function is overridden by our unit tests. - if (_Log.log) { - !this._updateDomImpl_renderedState.isOpenedMode && _Log.log("The CommandingSurface should only attempt to create an closed animation when it's not already closed"); - } - var openedHeight = this.getBoundingRects().commandingSurface.height, overflowAreaOpenedHeight = this._dom.overflowArea.offsetHeight, oldOverflowTop = this._dom.overflowArea.offsetTop, that = this; - return { - execute: function () { - _ElementUtilities.addClass(that.element, _Constants.ClassNames.closingClass); - return Animations._commandingSurfaceCloseAnimation({ - actionAreaClipper: that._dom.actionAreaContainer, - actionArea: that._dom.actionArea, - overflowAreaClipper: that._dom.overflowAreaContainer, - overflowArea: that._dom.overflowArea, - oldHeight: openedHeight, - newHeight: closedHeight, - overflowAreaHeight: overflowAreaOpenedHeight, - menuPositionedAbove: (that.overflowDirection === OverflowDirection.top), - }).then(function () { - _ElementUtilities.removeClass(that.element, _Constants.ClassNames.closingClass); - that._clearAnimation(); - }); - } - }; - }; - Object.defineProperty(_CommandingSurface.prototype, "initialized", { - get: function () { - return this._initializedSignal.promise; - }, - enumerable: true, - configurable: true - }); - _CommandingSurface.prototype._writeProfilerMark = function (text) { - _WriteProfilerMark("WinJS.UI._CommandingSurface:" + this._id + ":" + text); - }; - _CommandingSurface.prototype._initializeDom = function (root) { - var _this = this; - this._writeProfilerMark("_intializeDom,info"); - // Attaching JS control to DOM element - root["winControl"] = this; - this._id = root.id || _ElementUtilities._uniqueID(root); - if (!root.hasAttribute("tabIndex")) { - root.tabIndex = -1; - } - _ElementUtilities.addClass(root, _Constants.ClassNames.controlCssClass); - _ElementUtilities.addClass(root, _Constants.ClassNames.disposableCssClass); - var actionArea = _Global.document.createElement("div"); - _ElementUtilities.addClass(actionArea, _Constants.ClassNames.actionAreaCssClass); - _ElementUtilities._reparentChildren(root, actionArea); - var actionAreaContainer = _Global.document.createElement("div"); - _ElementUtilities.addClass(actionAreaContainer, _Constants.ClassNames.actionAreaContainerCssClass); - actionAreaContainer.appendChild(actionArea); - root.appendChild(actionAreaContainer); - var spacer = _Global.document.createElement("div"); - _ElementUtilities.addClass(spacer, _Constants.ClassNames.spacerCssClass); - actionArea.appendChild(spacer); - var overflowButton = _Global.document.createElement("button"); - overflowButton.tabIndex = 0; - overflowButton.innerHTML = ""; - _ElementUtilities.addClass(overflowButton, _Constants.ClassNames.overflowButtonCssClass); - actionArea.appendChild(overflowButton); - overflowButton.addEventListener("click", function () { - _this.opened = !_this.opened; - }); - var overflowArea = _Global.document.createElement("div"); - _ElementUtilities.addClass(overflowArea, _Constants.ClassNames.overflowAreaCssClass); - _ElementUtilities.addClass(overflowArea, _Constants.ClassNames.menuCssClass); - var overflowAreaContainer = _Global.document.createElement("div"); - _ElementUtilities.addClass(overflowAreaContainer, _Constants.ClassNames.overflowAreaContainerCssClass); - overflowAreaContainer.appendChild(overflowArea); - root.appendChild(overflowAreaContainer); - this._dom = { - root: root, - actionArea: actionArea, - actionAreaContainer: actionAreaContainer, - spacer: spacer, - overflowButton: overflowButton, - overflowArea: overflowArea, - overflowAreaContainer: overflowAreaContainer - }; - }; - _CommandingSurface.prototype._getFocusableElementsInfo = function () { - var _this = this; - var focusableCommandsInfo = { - elements: [], - focusedIndex: -1 - }; - var elementsInReach = Array.prototype.slice.call(this._dom.actionArea.children); - var elementsInReach = Array.prototype.slice.call(this._dom.actionArea.children); - if (this._dom.overflowArea.style.display !== "none") { - elementsInReach = elementsInReach.concat(Array.prototype.slice.call(this._dom.overflowArea.children)); - } - elementsInReach.forEach(function (element) { - if (_this._isElementFocusable(element)) { - focusableCommandsInfo.elements.push(element); - if (element.contains(_Global.document.activeElement)) { - focusableCommandsInfo.focusedIndex = focusableCommandsInfo.elements.length - 1; - } - } - }); - return focusableCommandsInfo; - }; - _CommandingSurface.prototype._dataUpdated = function () { - var _this = this; - this._primaryCommands = []; - this._secondaryCommands = []; - if (this.data.length > 0) { - this.data.forEach(function (command) { - if (command.section === "secondary") { - _this._secondaryCommands.push(command); - } - else { - _this._primaryCommands.push(command); - } - }); - } - this._dataDirty(); - this._machine.updateDom(); - }; - _CommandingSurface.prototype._refresh = function () { - var _this = this; - if (!this._refreshPending) { - this._refreshPending = true; - // Batch calls to _dataUpdated - Scheduler.schedule(function () { - if (_this._refreshPending && !_this._disposed) { - _this._refreshPending = false; - _this._dataUpdated(); - } - }, Scheduler.Priority.high, null, "WinJS.UI._CommandingSurface._refresh"); - } - }; - _CommandingSurface.prototype._addDataListeners = function () { - var _this = this; - this._dataChangedEvents.forEach(function (eventName) { - _this._data.addEventListener(eventName, _this._refreshBound, false); - }); - }; - _CommandingSurface.prototype._removeDataListeners = function () { - var _this = this; - this._dataChangedEvents.forEach(function (eventName) { - _this._data.removeEventListener(eventName, _this._refreshBound, false); - }); - }; - _CommandingSurface.prototype._isElementFocusable = function (element) { - var focusable = false; - if (element) { - var command = element["winControl"]; - if (command) { - focusable = command.element.style.display !== "none" && command.type !== _Constants.typeSeparator && !command.hidden && !command.disabled && (!command.firstElementFocus || command.firstElementFocus.tabIndex >= 0 || command.lastElementFocus.tabIndex >= 0); - } - else { - // e.g. the overflow button - focusable = element.style.display !== "none" && getComputedStyle(element).visibility !== "hidden" && element.tabIndex >= 0; - } - } - return focusable; - }; - _CommandingSurface.prototype._isCommandInActionArea = function (element) { - // Returns true if the element is a command in the actionarea, false otherwise - return element && element["winControl"] && element.parentElement === this._dom.actionArea; - }; - _CommandingSurface.prototype._getLastElementFocus = function (element) { - if (this._isCommandInActionArea(element)) { - // Only commands in the actionarea support lastElementFocus - return element["winControl"].lastElementFocus; - } - else { - return element; - } - }; - _CommandingSurface.prototype._getFirstElementFocus = function (element) { - if (this._isCommandInActionArea(element)) { - // Only commands in the actionarea support firstElementFocus - return element["winControl"].firstElementFocus; - } - else { - return element; - } - }; - _CommandingSurface.prototype._keyDownHandler = function (ev) { - if (!ev.altKey) { - if (_ElementUtilities._matchesSelector(ev.target, ".win-interactive, .win-interactive *")) { - return; - } - var Key = _ElementUtilities.Key; - var focusableElementsInfo = this._getFocusableElementsInfo(); - var targetCommand; - if (focusableElementsInfo.elements.length) { - switch (ev.keyCode) { - case (this._rtl ? Key.rightArrow : Key.leftArrow): - case Key.upArrow: - var index = Math.max(0, focusableElementsInfo.focusedIndex - 1); - targetCommand = this._getLastElementFocus(focusableElementsInfo.elements[index % focusableElementsInfo.elements.length]); - break; - case (this._rtl ? Key.leftArrow : Key.rightArrow): - case Key.downArrow: - var index = Math.min(focusableElementsInfo.focusedIndex + 1, focusableElementsInfo.elements.length - 1); - targetCommand = this._getFirstElementFocus(focusableElementsInfo.elements[index]); - break; - case Key.home: - var index = 0; - targetCommand = this._getFirstElementFocus(focusableElementsInfo.elements[index]); - break; - case Key.end: - var index = focusableElementsInfo.elements.length - 1; - targetCommand = this._getLastElementFocus(focusableElementsInfo.elements[index]); - break; - } - } - if (targetCommand && targetCommand !== _Global.document.activeElement) { - targetCommand.focus(); - ev.preventDefault(); - } - } - }; - _CommandingSurface.prototype._getDataFromDOMElements = function () { - this._writeProfilerMark("_getDataFromDOMElements,info"); - ControlProcessor.processAll(this._dom.actionArea, true); - var commands = []; - var childrenLength = this._dom.actionArea.children.length; - var child; - for (var i = 0; i < childrenLength; i++) { - child = this._dom.actionArea.children[i]; - if (child["winControl"] && child["winControl"] instanceof _Command.AppBarCommand) { - commands.push(child["winControl"]); - } - else if (child !== this._dom.overflowButton && child !== this._dom.spacer) { - throw new _ErrorFromName("WinJS.UI._CommandingSurface.MustContainCommands", strings.mustContainCommands); - } - } - return new BindingList.List(commands); - }; - _CommandingSurface.prototype._resizeHandler = function () { - if (this._dom.root.offsetWidth) { - var currentActionAreaWidth = _ElementUtilities._getPreciseContentWidth(this._dom.actionArea); - if (this._cachedMeasurements && this._cachedMeasurements.actionAreaContentBoxWidth !== currentActionAreaWidth) { - this._cachedMeasurements.actionAreaContentBoxWidth = currentActionAreaWidth; - this._layoutDirty(); - this._machine.updateDom(); - } - } - }; - _CommandingSurface.prototype._dataDirty = function () { - this._nextLayoutStage = Math.max(CommandLayoutPipeline.newDataStage, this._nextLayoutStage); - }; - _CommandingSurface.prototype._meaurementsDirty = function () { - this._nextLayoutStage = Math.max(CommandLayoutPipeline.measuringStage, this._nextLayoutStage); - }; - _CommandingSurface.prototype._layoutDirty = function () { - this._nextLayoutStage = Math.max(CommandLayoutPipeline.layoutStage, this._nextLayoutStage); - }; - _CommandingSurface.prototype.synchronousOpen = function () { - this._overflowAlignmentOffset = 0; - this._isOpenedMode = true; - this.updateDomImpl(); - this._overflowAlignmentOffset = this._computeAdjustedOverflowAreaOffset(); - this.updateDomImpl(); - }; - _CommandingSurface.prototype._computeAdjustedOverflowAreaOffset = function () { - // Returns any negative offset needed to prevent the shown overflowarea from clipping outside of the viewport. - // This function should only be called when CommandingSurface has been rendered in the opened state with - // an overflowAlignmentOffset of 0. - if (_Log.log) { - !this._updateDomImpl_renderedState.isOpenedMode && _Log.log("The CommandingSurface should only attempt to compute adjusted overflowArea offset " + " when it has been rendered opened"); - this._updateDomImpl_renderedState.overflowAlignmentOffset !== 0 && _Log.log("The CommandingSurface should only attempt to compute adjusted overflowArea offset " + " when it has been rendered with an overflowAlignementOffset of 0"); - } - var overflowArea = this._dom.overflowArea, boundingClientRects = this.getBoundingRects(), adjustedOffset = 0; - if (this._rtl) { - // In RTL the left edge of overflowarea prefers to align to the LEFT edge of the commandingSurface. - // Make sure we avoid clipping through the RIGHT edge of the viewport - var viewportRight = window.innerWidth, rightOffsetFromViewport = boundingClientRects.overflowArea.right; - adjustedOffset = Math.min(viewportRight - rightOffsetFromViewport, 0); - } - else { - // In LTR the right edge of overflowarea prefers to align to the RIGHT edge of the commandingSurface. - // Make sure we avoid clipping through the LEFT edge of the viewport. - var leftOffsetFromViewport = boundingClientRects.overflowArea.left; - adjustedOffset = Math.min(0, leftOffsetFromViewport); - } - return adjustedOffset; - }; - _CommandingSurface.prototype.synchronousClose = function () { - this._isOpenedMode = false; - this.updateDomImpl(); - }; - _CommandingSurface.prototype.updateDomImpl = function () { - this._updateDomImpl_renderDisplayMode(); - this._updateDomImpl_updateCommands(); - }; - _CommandingSurface.prototype._updateDomImpl_renderDisplayMode = function () { - var rendered = this._updateDomImpl_renderedState; - if (rendered.isOpenedMode !== this._isOpenedMode) { - if (this._isOpenedMode) { - // Render opened - removeClass(this._dom.root, _Constants.ClassNames.closedClass); - addClass(this._dom.root, _Constants.ClassNames.openedClass); - } - else { - // Render closed - removeClass(this._dom.root, _Constants.ClassNames.openedClass); - addClass(this._dom.root, _Constants.ClassNames.closedClass); - } - rendered.isOpenedMode = this._isOpenedMode; - } - if (rendered.closedDisplayMode !== this.closedDisplayMode) { - removeClass(this._dom.root, closedDisplayModeClassMap[rendered.closedDisplayMode]); - addClass(this._dom.root, closedDisplayModeClassMap[this.closedDisplayMode]); - rendered.closedDisplayMode = this.closedDisplayMode; - } - if (rendered.overflowDirection !== this.overflowDirection) { - removeClass(this._dom.root, overflowDirectionClassMap[rendered.overflowDirection]); - addClass(this._dom.root, overflowDirectionClassMap[this.overflowDirection]); - rendered.overflowDirection = this.overflowDirection; - } - if (this._overflowAlignmentOffset !== rendered.overflowAlignmentOffset) { - var offsetProperty = (this._rtl ? "left" : "right"); - var offsetTextValue = this._overflowAlignmentOffset + "px"; - this._dom.overflowAreaContainer.style[offsetProperty] = offsetTextValue; - } - }; - _CommandingSurface.prototype._updateDomImpl_updateCommands = function () { - this._writeProfilerMark("_updateDomImpl_updateCommands,info"); - var nextStage = this._nextLayoutStage; - while (nextStage !== CommandLayoutPipeline.idle) { - var currentStage = nextStage; - var okToProceed = false; - switch (currentStage) { - case CommandLayoutPipeline.newDataStage: - nextStage = CommandLayoutPipeline.measuringStage; - okToProceed = this._processNewData(); - break; - case CommandLayoutPipeline.measuringStage: - nextStage = CommandLayoutPipeline.layoutStage; - okToProceed = this._measure(); - break; - case CommandLayoutPipeline.layoutStage: - nextStage = CommandLayoutPipeline.idle; - okToProceed = this._layoutCommands(); - break; - } - if (!okToProceed) { - // If a stage fails, exit the loop and track that stage - // to be restarted the next time _updateCommands is run. - nextStage = currentStage; - break; - } - } - this._nextLayoutStage = nextStage; - if (nextStage === CommandLayoutPipeline.idle) { - // Callback for unit tests. - this._layoutCompleteCallback && this._layoutCompleteCallback(); - } - }; - _CommandingSurface.prototype._getDataChangeInfo = function () { - var i = 0, len = 0; - var added = []; - var deleted = []; - var affected = []; - var currentShown = []; - var currentElements = []; - var newShown = []; - var newHidden = []; - var newElements = []; - Array.prototype.forEach.call(this._dom.actionArea.querySelectorAll(_Constants.commandSelector), function (commandElement) { - if (commandElement.style.display !== "none") { - currentShown.push(commandElement); - } - currentElements.push(commandElement); - }); - this.data.forEach(function (command) { - if (command.element.style.display !== "none") { - newShown.push(command.element); - } - else { - newHidden.push(command.element); - } - newElements.push(command.element); - }); - deleted = diffElements(currentShown, newShown); - affected = diffElements(currentShown, deleted); - // "added" must also include the elements from "newHidden" to ensure that we continue - // to animate any command elements that have underflowed back into the actionarea - // as a part of this data change. - added = diffElements(newShown, currentShown).concat(newHidden); - return { - newElements: newElements, - currentElements: currentElements, - added: added, - deleted: deleted, - affected: affected, - }; - }; - _CommandingSurface.prototype._processNewData = function () { - var _this = this; - this._writeProfilerMark("_processNewData,info"); - var changeInfo = this._getDataChangeInfo(); - // Take a snapshot of the current state - var updateCommandAnimation = Animations._createUpdateListAnimation(changeInfo.added, changeInfo.deleted, changeInfo.affected); - // Unbind property mutation event listener from deleted IObservableCommands - changeInfo.deleted.forEach(function (deletedElement) { - var command = (deletedElement['winControl']); - if (command && command['_propertyMutations']) { - command._propertyMutations.unbind(_this._refreshBound); - } - }); - // Bind property mutation event listener to added IObservable commands. - changeInfo.added.forEach(function (deletedElement) { - var command = (deletedElement['winControl']); - if (command && command['_propertyMutations']) { - command._propertyMutations.bind(_this._refreshBound); - } - }); - // Remove current ICommand elements - changeInfo.currentElements.forEach(function (element) { - if (element.parentElement) { - element.parentElement.removeChild(element); - } - }); - // Add new ICommand elements in the right order. - changeInfo.newElements.forEach(function (element) { - _this._dom.actionArea.appendChild(element); - }); - // Ensure that the overflow button is always the last element in the actionarea - this._dom.actionArea.appendChild(this._dom.overflowButton); - if (this.data.length > 0) { - _ElementUtilities.removeClass(this._dom.root, _Constants.ClassNames.emptyCommandingSurfaceCssClass); - } - else { - _ElementUtilities.addClass(this._dom.root, _Constants.ClassNames.emptyCommandingSurfaceCssClass); - } - // Execute the animation. - updateCommandAnimation.execute(); - // Indicate processing was successful. - return true; - }; - _CommandingSurface.prototype._measure = function () { - var _this = this; - this._writeProfilerMark("_measure,info"); - var canMeasure = (_Global.document.body.contains(this._dom.root) && this._dom.actionArea.offsetWidth > 0); - if (canMeasure) { - var overflowButtonWidth = _ElementUtilities._getPreciseTotalWidth(this._dom.overflowButton), actionAreaContentBoxWidth = _ElementUtilities._getPreciseContentWidth(this._dom.actionArea), separatorWidth = 0, standardCommandWidth = 0, contentCommandWidths = {}; - this._primaryCommands.forEach(function (command) { - // Ensure that the element we are measuring does not have display: none (e.g. it was just added, and it - // will be animated in) - var originalDisplayStyle = command.element.style.display; - command.element.style.display = ""; - if (command.type === _Constants.typeContent) { - // Measure each 'content' command type that we find - contentCommandWidths[_this._commandUniqueId(command)] = _ElementUtilities._getPreciseTotalWidth(command.element); - } - else if (command.type === _Constants.typeSeparator) { - // Measure the first 'separator' command type we find. - if (!separatorWidth) { - separatorWidth = _ElementUtilities._getPreciseTotalWidth(command.element); - } - } - else { - // Button, toggle, 'flyout' command types have the same width. Measure the first one we find. - if (!standardCommandWidth) { - standardCommandWidth = _ElementUtilities._getPreciseTotalWidth(command.element); - } - } - // Restore the original display style - command.element.style.display = originalDisplayStyle; - }); - this._cachedMeasurements = { - contentCommandWidths: contentCommandWidths, - separatorWidth: separatorWidth, - standardCommandWidth: standardCommandWidth, - overflowButtonWidth: overflowButtonWidth, - actionAreaContentBoxWidth: actionAreaContentBoxWidth, - }; - // Indicate measure was successful - return true; - } - else { - // Indicate measure was unsuccessful - return false; - } - }; - _CommandingSurface.prototype._layoutCommands = function () { - var _this = this; - this._writeProfilerMark("_layoutCommands,StartTM"); - // - // Filter commands that will not be visible in the actionarea - // - this._primaryCommands.forEach(function (command) { - command.element.style.display = (command.hidden ? "none" : ""); - }); - var primaryCommandsLocation = this._getVisiblePrimaryCommandsLocation(); - this._hideSeparatorsIfNeeded(primaryCommandsLocation.actionArea); - // Primary commands that will be mirrored in the overflow area should be hidden so - // that they are not visible in the actionarea. - primaryCommandsLocation.overflowArea.forEach(function (command) { - command.element.style.display = "none"; - }); - // The secondary commands in the actionarea should be hidden since they are always - // mirrored as new elements in the overflow area. - this._secondaryCommands.forEach(function (command) { - command.element.style.display = "none"; - }); - var overflowCommands = primaryCommandsLocation.overflowArea; - var showOverflowButton = (overflowCommands.length > 0 || this._secondaryCommands.length > 0); - this._dom.overflowButton.style.display = showOverflowButton ? "" : "none"; - // Set up a custom content flyout if there will be "content" typed commands in the overflowarea. - var isCustomContent = function (command) { - return command.type === _Constants.typeContent; - }; - var hasCustomContent = overflowCommands.some(isCustomContent) || this._secondaryCommands.some(isCustomContent); - if (hasCustomContent && !this._contentFlyout) { - this._contentFlyoutInterior = _Global.document.createElement("div"); - _ElementUtilities.addClass(this._contentFlyoutInterior, _Constants.ClassNames.contentFlyoutCssClass); - this._contentFlyout = new _Flyout.Flyout(); - this._contentFlyout.element.appendChild(this._contentFlyoutInterior); - _Global.document.body.appendChild(this._contentFlyout.element); - this._contentFlyout.onbeforeshow = function () { - _ElementUtilities.empty(_this._contentFlyoutInterior); - _ElementUtilities._reparentChildren(_this._chosenCommand.element, _this._contentFlyoutInterior); - }; - this._contentFlyout.onafterhide = function () { - _ElementUtilities._reparentChildren(_this._contentFlyoutInterior, _this._chosenCommand.element); - }; - } - // - // Project overflowing and secondary commands into the overflowArea as MenuCommands - // - // Clean up previous MenuCommand projections - _ElementUtilities.empty(this._dom.overflowArea); - this._menuCommandProjections.map(function (menuCommand) { - if (_this._contentFlyout && menuCommand.flyout === _this._contentFlyout) { - // Prevent our _contentFlyout from being disposed with the MenuCommand. - menuCommand.flyout = null; - } - menuCommand.dispose(); - }); - var hasToggleCommands = false, menuCommandProjections = []; - // Add primary commands that have overflowed. - overflowCommands.forEach(function (command) { - if (command.type === _Constants.typeToggle) { - hasToggleCommands = true; - } - menuCommandProjections.push(_this._projectAsMenuCommand(command)); - }); - // Add separator between primary and secondary command if applicable - var secondaryCommandsLength = this._secondaryCommands.length; - if (overflowCommands.length > 0 && secondaryCommandsLength > 0) { - var separator = new _CommandingSurfaceMenuCommand._MenuCommand(null, { - type: _Constants.typeSeparator - }); - menuCommandProjections.push(separator); - } - // Add secondary commands - this._secondaryCommands.forEach(function (command) { - if (!command.hidden) { - if (command.type === _Constants.typeToggle) { - hasToggleCommands = true; - } - menuCommandProjections.push(_this._projectAsMenuCommand(command)); - } - }); - this._hideSeparatorsIfNeeded(menuCommandProjections); - menuCommandProjections.forEach(function (command) { - _this._dom.overflowArea.appendChild(command.element); - }); - this._menuCommandProjections = menuCommandProjections; - _ElementUtilities[hasToggleCommands ? "addClass" : "removeClass"](this._dom.overflowArea, _Constants.ClassNames.menuContainsToggleCommandClass); - this._writeProfilerMark("_layoutCommands,StopTM"); - // Indicate layout was successful. - return true; - }; - _CommandingSurface.prototype._commandUniqueId = function (command) { - return _ElementUtilities._uniqueID(command.element); - }; - _CommandingSurface.prototype._getVisiblePrimaryCommandsInfo = function () { - var width = 0; - var commands = []; - var priority = 0; - var currentAssignedPriority = 0; - for (var i = this._primaryCommands.length - 1; i >= 0; i--) { - var command = this._primaryCommands[i]; - if (!command.hidden) { - if (command.priority === undefined) { - priority = currentAssignedPriority--; - } - else { - priority = command.priority; - } - width = (command.element.style.display === "none" ? 0 : this._getCommandWidth(command)); - commands.unshift({ - command: command, - width: width, - priority: priority - }); - } - } - return commands; - }; - _CommandingSurface.prototype._getVisiblePrimaryCommandsLocation = function () { - this._writeProfilerMark("_getVisiblePrimaryCommandsLocation,info"); - var actionAreaCommands = []; - var overflowAreaCommands = []; - var overflowButtonSpace = 0; - var hasSecondaryCommands = this._secondaryCommands.length > 0; - var commandsInfo = this._getVisiblePrimaryCommandsInfo(); - var sortedCommandsInfo = commandsInfo.slice(0).sort(function (commandInfo1, commandInfo2) { - return commandInfo1.priority - commandInfo2.priority; - }); - var maxPriority = Number.MAX_VALUE; - var availableWidth = this._cachedMeasurements.actionAreaContentBoxWidth; - for (var i = 0, len = sortedCommandsInfo.length; i < len; i++) { - availableWidth -= sortedCommandsInfo[i].width; - // The overflow button needs space if there are secondary commands, or we are not evaluating the last command. - overflowButtonSpace = (hasSecondaryCommands || (i < len - 1) ? this._cachedMeasurements.overflowButtonWidth : 0); - if (availableWidth - overflowButtonSpace < 0) { - maxPriority = sortedCommandsInfo[i].priority - 1; - break; - } - } - commandsInfo.forEach(function (commandInfo) { - if (commandInfo.priority <= maxPriority) { - actionAreaCommands.push(commandInfo.command); - } - else { - overflowAreaCommands.push(commandInfo.command); - } - }); - return { - actionArea: actionAreaCommands, - overflowArea: overflowAreaCommands - }; - }; - _CommandingSurface.prototype._getCommandWidth = function (command) { - if (command.type === _Constants.typeContent) { - return this._cachedMeasurements.contentCommandWidths[this._commandUniqueId(command)]; - } - else if (command.type === _Constants.typeSeparator) { - return this._cachedMeasurements.separatorWidth; - } - else { - return this._cachedMeasurements.standardCommandWidth; - } - }; - _CommandingSurface.prototype._projectAsMenuCommand = function (originalCommand) { - var _this = this; - var menuCommand = new _CommandingSurfaceMenuCommand._MenuCommand(null, { - label: originalCommand.label, - type: (originalCommand.type === _Constants.typeContent ? _Constants.typeFlyout : originalCommand.type) || _Constants.typeButton, - disabled: originalCommand.disabled, - flyout: originalCommand.flyout, - beforeInvoke: function () { - // Save the command that was selected - _this._chosenCommand = (menuCommand["_originalICommand"]); - // If this WinJS.UI.MenuCommand has type: toggle, we should also toggle the value of the original WinJS.UI.Command - if (_this._chosenCommand.type === _Constants.typeToggle) { - _this._chosenCommand.selected = !_this._chosenCommand.selected; - } - } - }); - if (originalCommand.selected) { - menuCommand.selected = true; - } - if (originalCommand.extraClass) { - menuCommand.extraClass = originalCommand.extraClass; - } - if (originalCommand.type === _Constants.typeContent) { - if (!menuCommand.label) { - menuCommand.label = _Constants.contentMenuCommandDefaultLabel; - } - menuCommand.flyout = this._contentFlyout; - } - else { - menuCommand.onclick = originalCommand.onclick; - } - menuCommand["_originalICommand"] = originalCommand; - return menuCommand; - }; - _CommandingSurface.prototype._hideSeparatorsIfNeeded = function (commands) { - var prevType = _Constants.typeSeparator; - var command; - // Hide all leading or consecutive separators - var commandsLength = commands.length; - commands.forEach(function (command) { - if (command.type === _Constants.typeSeparator && prevType === _Constants.typeSeparator) { - command.element.style.display = "none"; - } - prevType = command.type; - }); - for (var i = commandsLength - 1; i >= 0; i--) { - command = commands[i]; - if (command.type === _Constants.typeSeparator) { - command.element.style.display = "none"; - } - else { - break; - } - } - }; - _CommandingSurface.prototype._clearAnimation = function () { - var transformScriptName = _BaseUtils._browserStyleEquivalents["transform"].scriptName; - this._dom.actionAreaContainer.style[transformScriptName] = ""; - this._dom.actionArea.style[transformScriptName] = ""; - this._dom.overflowAreaContainer.style[transformScriptName] = ""; - this._dom.overflowArea.style[transformScriptName] = ""; - }; - /// Display options for the actionarea when the _CommandingSurface is closed. - _CommandingSurface.ClosedDisplayMode = ClosedDisplayMode; - /// Display options used by the _Commandingsurface to determine which direction it should expand when opening. - _CommandingSurface.OverflowDirection = OverflowDirection; - _CommandingSurface.supportedForProcessing = true; - return _CommandingSurface; - })(); - exports._CommandingSurface = _CommandingSurface; - _Base.Class.mix(_CommandingSurface, _Events.createEventProperties(_Constants.EventNames.beforeOpen, _Constants.EventNames.afterOpen, _Constants.EventNames.beforeClose, _Constants.EventNames.afterClose)); - // addEventListener, removeEventListener, dispatchEvent - _Base.Class.mix(_CommandingSurface, _Control.DOMEventMixin); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/CommandingSurface',["require", "exports"], function (require, exports) { - var module = null; - function getModule() { - if (!module) { - require(["./CommandingSurface/_CommandingSurface"], function (m) { - module = m; - }); - } - return module._CommandingSurface; - } - var publicMembers = Object.create({}, { - _CommandingSurface: { - get: function () { - return getModule(); - } - } - }); - return publicMembers; -}); - - -define('require-style!less/styles-toolbar',[],function(){}); -define('WinJS/Controls/ToolBar/_ToolBar',["require", "exports", "../../Core/_Base", "../ToolBar/_Constants", "../CommandingSurface", "../../Utilities/_Control", "../../Utilities/_Dispose", "../../Utilities/_ElementUtilities", "../../Core/_ErrorFromName", '../../Core/_Events', "../../Core/_Global", '../../_LightDismissService', "../../Core/_Resources", '../../Utilities/_OpenCloseMachine', "../../Core/_WriteProfilerMark"], function (require, exports, _Base, _Constants, _CommandingSurface, _Control, _Dispose, _ElementUtilities, _ErrorFromName, _Events, _Global, _LightDismissService, _Resources, _OpenCloseMachine, _WriteProfilerMark) { - require(["require-style!less/styles-toolbar"]); - "use strict"; - var strings = { - get ariaLabel() { - return _Resources._getWinJSString("ui/toolbarAriaLabel").value; - }, - get overflowButtonAriaLabel() { - return _Resources._getWinJSString("ui/toolbarOverflowButtonAriaLabel").value; - }, - get mustContainCommands() { - return "The toolbar can only contain WinJS.UI.Command or WinJS.UI.AppBarCommand controls"; - }, - get duplicateConstruction() { - return "Invalid argument: Controls may only be instantiated one time for each DOM element"; - } - }; - var ClosedDisplayMode = { - /// - /// When the ToolBar is closed, the height of the ToolBar is reduced such that button commands are still visible, but their labels are hidden. - /// - compact: "compact", - /// - /// When the ToolBar is closed, the height of the ToolBar is always sized to content. - /// - full: "full", - }; - var closedDisplayModeClassMap = {}; - closedDisplayModeClassMap[ClosedDisplayMode.compact] = _Constants.ClassNames.compactClass; - closedDisplayModeClassMap[ClosedDisplayMode.full] = _Constants.ClassNames.fullClass; - // Versions of add/removeClass that are no ops when called with falsy class names. - function addClass(element, className) { - className && _ElementUtilities.addClass(element, className); - } - function removeClass(element, className) { - className && _ElementUtilities.removeClass(element, className); - } - /// - /// - /// Displays ICommands within the flow of the app. Use the ToolBar around other statically positioned app content. - /// - /// - /// - /// - /// - /// - /// ]]> - /// The entire ToolBar control. - /// The toolbar overflow button. - /// The container for toolbar commands that overflow. - /// - /// - var ToolBar = (function () { - function ToolBar(element, options) { - /// - /// - /// Creates a new ToolBar control. - /// - /// - /// The DOM element that will host the control. - /// - /// - /// The set of properties and values to apply to the new ToolBar control. - /// - /// - /// The new ToolBar control. - /// - /// - var _this = this; - if (options === void 0) { options = {}; } - // State private to the _updateDomImpl family of method. No other methods should make use of it. - // - // Nothing has been rendered yet so these are all initialized to undefined. Because - // they are undefined, the first time _updateDomImpl is called, they will all be - // rendered. - this._updateDomImpl_renderedState = { - isOpenedMode: undefined, - closedDisplayMode: undefined, - prevInlineWidth: undefined, - }; - this._writeProfilerMark("constructor,StartTM"); - // Check to make sure we weren't duplicated - if (element && element["winControl"]) { - throw new _ErrorFromName("WinJS.UI.ToolBar.DuplicateConstruction", strings.duplicateConstruction); - } - this._initializeDom(element || _Global.document.createElement("div")); - var stateMachine = new _OpenCloseMachine.OpenCloseMachine({ - eventElement: this.element, - onOpen: function () { - var openAnimation = _this._commandingSurface.createOpenAnimation(_this._getClosedHeight()); - _this._synchronousOpen(); - return openAnimation.execute(); - }, - onClose: function () { - var closeAnimation = _this._commandingSurface.createCloseAnimation(_this._getClosedHeight()); - return closeAnimation.execute().then(function () { - _this._synchronousClose(); - }); - }, - onUpdateDom: function () { - _this._updateDomImpl(); - }, - onUpdateDomWithIsOpened: function (isOpened) { - _this._isOpenedMode = isOpened; - _this._updateDomImpl(); - } - }); - // Events - this._handleShowingKeyboardBound = this._handleShowingKeyboard.bind(this); - _ElementUtilities._inputPaneListener.addEventListener(this._dom.root, "showing", this._handleShowingKeyboardBound); - // Initialize private state. - this._disposed = false; - this._cachedClosedHeight = null; - this._commandingSurface = new _CommandingSurface._CommandingSurface(this._dom.commandingSurfaceEl, { openCloseMachine: stateMachine }); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-actionarea"), _Constants.ClassNames.actionAreaCssClass); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowarea"), _Constants.ClassNames.overflowAreaCssClass); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowbutton"), _Constants.ClassNames.overflowButtonCssClass); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-ellipsis"), _Constants.ClassNames.ellipsisCssClass); - this._isOpenedMode = _Constants.defaultOpened; - this._dismissable = new _LightDismissService.LightDismissableElement({ - element: this._dom.root, - tabIndex: this._dom.root.hasAttribute("tabIndex") ? this._dom.root.tabIndex : -1, - onLightDismiss: function () { - _this.close(); - } - }); - // Initialize public properties. - this.closedDisplayMode = _Constants.defaultClosedDisplayMode; - this.opened = this._isOpenedMode; - _Control.setOptions(this, options); - // Exit the Init state. - _ElementUtilities._inDom(this.element).then(function () { - return _this._commandingSurface.initialized; - }).then(function () { - stateMachine.exitInit(); - _this._writeProfilerMark("constructor,StopTM"); - }); - } - Object.defineProperty(ToolBar.prototype, "element", { - /// - get: function () { - return this._dom.root; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ToolBar.prototype, "data", { - /// - /// Gets or sets the Binding List of WinJS.UI.Command for the ToolBar. - /// - get: function () { - return this._commandingSurface.data; - }, - set: function (value) { - this._commandingSurface.data = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ToolBar.prototype, "closedDisplayMode", { - /// - /// Gets or sets the closedDisplayMode for the ToolBar. Values are "compact" and "full". - /// - get: function () { - return this._commandingSurface.closedDisplayMode; - }, - set: function (value) { - if (ClosedDisplayMode[value]) { - this._commandingSurface.closedDisplayMode = value; - this._cachedClosedHeight = null; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ToolBar.prototype, "opened", { - /// - get: function () { - return this._commandingSurface.opened; - }, - set: function (value) { - this._commandingSurface.opened = value; - }, - enumerable: true, - configurable: true - }); - ToolBar.prototype.open = function () { - /// - /// - /// Opens the ToolBar - /// - /// - this._commandingSurface.open(); - }; - ToolBar.prototype.close = function () { - /// - /// - /// Closes the ToolBar - /// - /// - this._commandingSurface.close(); - }; - ToolBar.prototype.dispose = function () { - /// - /// - /// Disposes this ToolBar. - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - _LightDismissService.hidden(this._dismissable); - // Disposing the _commandingSurface will trigger dispose on its OpenCloseMachine and synchronously complete any animations that might have been running. - this._commandingSurface.dispose(); - // If page navigation is happening, we don't want the ToolBar left behind in the body. - // Synchronoulsy close the ToolBar to force it out of the body and back into its parent element. - this._synchronousClose(); - _ElementUtilities._inputPaneListener.removeEventListener(this._dom.root, "showing", this._handleShowingKeyboardBound); - _Dispose.disposeSubTree(this.element); - }; - ToolBar.prototype.forceLayout = function () { - /// - /// - /// Forces the ToolBar to update its layout. Use this function when the window did not change size, but the container of the ToolBar changed size. - /// - /// - this._commandingSurface.forceLayout(); - }; - ToolBar.prototype.getCommandById = function (id) { - /// - /// - /// Retrieves the command with the specified ID from this ToolBar. - /// If more than one command is found, this method returns the first command found. - /// - /// Id of the command to return. - /// - /// The command found, or null if no command is found. - /// - /// - return this._commandingSurface.getCommandById(id); - }; - ToolBar.prototype.showOnlyCommands = function (commands) { - /// - /// - /// Show the specified commands, hiding all of the others in the ToolBar. - /// - /// - /// An array of the commands to show. The array elements may be Command objects, or the string identifiers (IDs) of commands. - /// - /// - return this._commandingSurface.showOnlyCommands(commands); - }; - ToolBar.prototype._writeProfilerMark = function (text) { - _WriteProfilerMark("WinJS.UI.ToolBar:" + this._id + ":" + text); - }; - ToolBar.prototype._initializeDom = function (root) { - this._writeProfilerMark("_intializeDom,info"); - // Attaching JS control to DOM element - root["winControl"] = this; - this._id = root.id || _ElementUtilities._uniqueID(root); - _ElementUtilities.addClass(root, _Constants.ClassNames.controlCssClass); - _ElementUtilities.addClass(root, _Constants.ClassNames.disposableCssClass); - // Make sure we have an ARIA role - var role = root.getAttribute("role"); - if (!role) { - root.setAttribute("role", "menubar"); - } - var label = root.getAttribute("aria-label"); - if (!label) { - root.setAttribute("aria-label", strings.ariaLabel); - } - // Create element for commandingSurface and reparent any declarative Commands. - // The CommandingSurface constructor will parse child elements as AppBarCommands. - var commandingSurfaceEl = document.createElement("DIV"); - _ElementUtilities._reparentChildren(root, commandingSurfaceEl); - root.appendChild(commandingSurfaceEl); - // While the ToolBar is open, it will place itself in the so it can become a light dismissible - // overlay. It leaves the placeHolder element behind as stand in at the ToolBar's original DOM location - // to avoid reflowing surrounding app content and create the illusion that the ToolBar hasn't moved along - // the x or y planes. - var placeHolder = _Global.document.createElement("DIV"); - _ElementUtilities.addClass(placeHolder, _Constants.ClassNames.placeHolderCssClass); - // If the ToolBar's original HTML parent node is disposed while the ToolBar is open and repositioned as - // a temporary child of the , make sure that calling dispose on the placeHolder element will trigger - // dispose on the ToolBar as well. - _Dispose.markDisposable(placeHolder, this.dispose.bind(this)); - this._dom = { - root: root, - commandingSurfaceEl: commandingSurfaceEl, - placeHolder: placeHolder, - }; - }; - ToolBar.prototype._handleShowingKeyboard = function (event) { - // Because the ToolBar takes up layout space and is not an overlay, it doesn't have the same expectation - // to move itself to get out of the way of a showing IHM. Instsead we just close the ToolBar to avoid - // scenarios where the ToolBar is occluded, but the click-eating-div is still present since it may seem - // strange to end users that an occluded ToolBar (out of sight, out of mind) is still eating their first - // click. - // Mitigation: - // Because (1) custom content in a ToolBar can only be included as a 'content' type command, because (2) - // the ToolBar only supports closedDisplayModes 'compact' and 'full', and because (3) 'content' type - // commands in the overflowarea use a separate contentflyout to display their contents: - // Interactable custom content contained within the ToolBar actionarea or overflowarea, will remain - // visible and interactable even when showing the IHM closes the ToolBar. - this.close(); - }; - ToolBar.prototype._synchronousOpen = function () { - this._isOpenedMode = true; - this._updateDomImpl(); - }; - ToolBar.prototype._synchronousClose = function () { - this._isOpenedMode = false; - this._updateDomImpl(); - }; - ToolBar.prototype._updateDomImpl = function () { - var rendered = this._updateDomImpl_renderedState; - if (rendered.isOpenedMode !== this._isOpenedMode) { - if (this._isOpenedMode) { - this._updateDomImpl_renderOpened(); - } - else { - this._updateDomImpl_renderClosed(); - } - rendered.isOpenedMode = this._isOpenedMode; - } - if (rendered.closedDisplayMode !== this.closedDisplayMode) { - removeClass(this._dom.root, closedDisplayModeClassMap[rendered.closedDisplayMode]); - addClass(this._dom.root, closedDisplayModeClassMap[this.closedDisplayMode]); - rendered.closedDisplayMode = this.closedDisplayMode; - } - this._commandingSurface.updateDomImpl(); - }; - ToolBar.prototype._getClosedHeight = function () { - if (this._cachedClosedHeight === null) { - var wasOpen = this._isOpenedMode; - if (this._isOpenedMode) { - this._synchronousClose(); - } - this._cachedClosedHeight = this._commandingSurface.getBoundingRects().commandingSurface.height; - if (wasOpen) { - this._synchronousOpen(); - } - } - return this._cachedClosedHeight; - }; - ToolBar.prototype._updateDomImpl_renderOpened = function () { - var _this = this; - // Measure closed state. - this._updateDomImpl_renderedState.prevInlineWidth = this._dom.root.style.width; - var closedBorderBox = this._dom.root.getBoundingClientRect(); - var closedContentWidth = _ElementUtilities._getPreciseContentWidth(this._dom.root); - var closedContentHeight = _ElementUtilities._getPreciseContentHeight(this._dom.root); - var closedStyle = getComputedStyle(this._dom.root); - var closedPaddingTop = _ElementUtilities._convertToPrecisePixels(closedStyle.paddingTop); - var closedBorderTop = _ElementUtilities._convertToPrecisePixels(closedStyle.borderTopWidth); - var closedMargins = _ElementUtilities._getPreciseMargins(this._dom.root); - var closedContentBoxTop = closedBorderBox.top + closedBorderTop + closedPaddingTop; - var closedContentBoxBottom = closedContentBoxTop + closedContentHeight; - // Size our placeHolder. Set height and width to match borderbox of the closed ToolBar. - // Copy ToolBar margins to the placeholder. - var placeHolder = this._dom.placeHolder; - var placeHolderStyle = placeHolder.style; - placeHolderStyle.width = closedBorderBox.width + "px"; - placeHolderStyle.height = closedBorderBox.height + "px"; - placeHolderStyle.marginTop = closedMargins.top + "px"; - placeHolderStyle.marginRight = closedMargins.right + "px"; - placeHolderStyle.marginBottom = closedMargins.bottom + "px"; - placeHolderStyle.marginLeft = closedMargins.left + "px"; - _ElementUtilities._maintainFocus(function () { - // Move ToolBar element to the body in preparation of becoming a light dismissible. Leave an equal sized placeHolder element - // at our original DOM location to avoid reflowing surrounding app content. - _this._dom.root.parentElement.insertBefore(placeHolder, _this._dom.root); - _Global.document.body.appendChild(_this._dom.root); - // Position the ToolBar to completely cover the same region as the placeholder element. - _this._dom.root.style.width = closedContentWidth + "px"; - _this._dom.root.style.left = closedBorderBox.left - closedMargins.left + "px"; - // Determine which direction to expand the CommandingSurface elements when opened. The overflow area will be rendered at the corresponding edge of - // the ToolBar's content box, so we choose the direction that offers the most space between that edge and the corresponding edge of the viewport. - // This is to reduce the chance that the overflow area might clip through the edge of the viewport. - var topOfViewport = 0; - var bottomOfViewport = _Global.innerHeight; - var distanceFromTop = closedContentBoxTop - topOfViewport; - var distanceFromBottom = bottomOfViewport - closedContentBoxBottom; - if (distanceFromTop > distanceFromBottom) { - // CommandingSurface is going to expand updwards. - _this._commandingSurface.overflowDirection = _Constants.OverflowDirection.top; - // Position the bottom edge of the ToolBar marginbox over the bottom edge of the placeholder marginbox. - _this._dom.root.style.bottom = (bottomOfViewport - closedBorderBox.bottom) - closedMargins.bottom + "px"; - } - else { - // CommandingSurface is going to expand downwards. - _this._commandingSurface.overflowDirection = _Constants.OverflowDirection.bottom; - // Position the top edge of the ToolBar marginbox over the top edge of the placeholder marginbox. - _this._dom.root.style.top = (topOfViewport + closedBorderBox.top) - closedMargins.top + "px"; - } - // Render opened state - _ElementUtilities.addClass(_this._dom.root, _Constants.ClassNames.openedClass); - _ElementUtilities.removeClass(_this._dom.root, _Constants.ClassNames.closedClass); - }); - this._commandingSurface.synchronousOpen(); - _LightDismissService.shown(this._dismissable); // Call at the start of the open animation - }; - ToolBar.prototype._updateDomImpl_renderClosed = function () { - var _this = this; - _ElementUtilities._maintainFocus(function () { - if (_this._dom.placeHolder.parentElement) { - // Restore our placement in the DOM - var placeHolder = _this._dom.placeHolder; - placeHolder.parentElement.insertBefore(_this._dom.root, placeHolder); - placeHolder.parentElement.removeChild(placeHolder); - } - // Render Closed - _this._dom.root.style.top = ""; - _this._dom.root.style.right = ""; - _this._dom.root.style.bottom = ""; - _this._dom.root.style.left = ""; - _this._dom.root.style.width = _this._updateDomImpl_renderedState.prevInlineWidth; - _ElementUtilities.addClass(_this._dom.root, _Constants.ClassNames.closedClass); - _ElementUtilities.removeClass(_this._dom.root, _Constants.ClassNames.openedClass); - }); - this._commandingSurface.synchronousClose(); - _LightDismissService.hidden(this._dismissable); // Call after the close animation - }; - /// - /// Display options for the actionarea when the ToolBar is closed. - /// - ToolBar.ClosedDisplayMode = ClosedDisplayMode; - ToolBar.supportedForProcessing = true; - return ToolBar; - })(); - exports.ToolBar = ToolBar; - _Base.Class.mix(ToolBar, _Events.createEventProperties(_Constants.EventNames.beforeOpen, _Constants.EventNames.afterOpen, _Constants.EventNames.beforeClose, _Constants.EventNames.afterClose)); - // addEventListener, removeEventListener, dispatchEvent - _Base.Class.mix(ToolBar, _Control.DOMEventMixin); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/ToolBar',["require", "exports", '../Core/_Base'], function (require, exports, _Base) { - var module = null; - _Base.Namespace.define("WinJS.UI", { - ToolBar: { - get: function () { - if (!module) { - require(["./ToolBar/_ToolBar"], function (m) { - module = m; - }); - } - return module.ToolBar; - } - } - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/_LegacyAppBar/_Layouts',[ - 'exports', - '../../Animations/_TransitionAnimation', - '../../BindingList', - '../../Core/_BaseUtils', - '../../Core/_Global', - '../../Core/_Base', - '../../Core/_ErrorFromName', - '../../Core/_Resources', - '../../Core/_WriteProfilerMark', - '../../Controls/ToolBar', - '../../Controls/ToolBar/_Constants', - '../../Promise', - '../../Scheduler', - '../../Utilities/_Control', - '../../Utilities/_Dispose', - '../../Utilities/_ElementUtilities', - '../AppBar/_Command', - './_Constants' -], function appBarLayoutsInit(exports, _TransitionAnimation, BindingList, _BaseUtils, _Global, _Base, _ErrorFromName, _Resources, _WriteProfilerMark, ToolBar, _ToolBarConstants, Promise, Scheduler, _Control, _Dispose, _ElementUtilities, _Command, _Constants) { - "use strict"; - - // AppBar will use this when AppBar.layout property is set to "custom" - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - _AppBarBaseLayout: _Base.Namespace._lazy(function () { - var baseType = _Constants.appBarLayoutCustom; - - var strings = { - get nullCommand() { return "Invalid argument: command must not be null"; } - }; - - var _AppBarBaseLayout = _Base.Class.define(function _AppBarBaseLayout_ctor(appBarEl, options) { - this._disposed = false; - - options = options || {}; - _Control.setOptions(this, options); - - if (appBarEl) { - this.connect(appBarEl); - } - }, { - // Members - className: { - get: function _AppBarBaseLayout_get_className() { - return this._className; - }, - }, - type: { - get: function _AppBarBaseLayout_get_className() { - return this._type || baseType; - }, - }, - commandsInOrder: { - get: function _AppBarBaseLayout_get_commandsInOrder() { - // Get a DOM ordered collection of the AppBarCommand elements in the AppBar. - var commandElements = this.appBarEl.querySelectorAll("." + _Constants.appBarCommandClass); - - // Return an array of AppBarCommand objects. - return Array.prototype.map.call(commandElements, function (commandElement) { - return commandElement.winControl; - }); - } - }, - connect: function _AppBarBaseLayout_connect(appBarEl) { - if (this.className) { - _ElementUtilities.addClass(appBarEl, this.className); - } - this.appBarEl = appBarEl; - }, - disconnect: function _AppBarBaseLayout_disconnect() { - if (this.className) { - _ElementUtilities.removeClass(this.appBarEl, this.className); - } - this.appBarEl = null; - this.dispose(); - }, - layout: function _AppBarBaseLayout_layout(commands) { - // Append commands to the DOM. - var len = commands.length; - for (var i = 0; i < len; i++) { - var command = this.sanitizeCommand(commands[i]); - this.appBarEl.appendChild(command._element); - } - }, - showCommands: function _AppBarBaseLayout_showCommands(commands) { - // Use the default overlay showCommands implementation - this.appBarEl.winControl._showCommands(commands); - }, - showOnlyCommands: function _AppBarBaseLayout_showOnlyCommands(commands) { - // Use the default overlay _showOnlyCommands implementation - this.appBarEl.winControl._showOnlyCommands(commands); - }, - hideCommands: function _AppBarBaseLayout_hideCommands(commands) { - // Use the default overlay _hideCommands implementation - this.appBarEl.winControl._hideCommands(commands); - }, - sanitizeCommand: function _AppBarBaseLayout_sanitizeCommand(command) { - if (!command) { - throw new _ErrorFromName("WinJS.UI.AppBar.NullCommand", strings.nullCommand); - } - // See if it's a command already - command = command.winControl || command; - if (!command._element) { - // Not a command, so assume it is options for the command's constructor. - command = new _Command.AppBarCommand(null, command); - } - // If we were attached somewhere else, detach us - if (command._element.parentElement) { - command._element.parentElement.removeChild(command._element); - } - - return command; - }, - dispose: function _AppBarBaseLayout_dispose() { - this._disposed = true; - }, - disposeChildren: function _AppBarBaseLayout_disposeChildren() { - var appBarFirstDiv = this.appBarEl.querySelectorAll("." + _Constants.firstDivClass); - appBarFirstDiv = appBarFirstDiv.length >= 1 ? appBarFirstDiv[0] : null; - var appBarFinalDiv = this.appBarEl.querySelectorAll("." + _Constants.finalDivClass); - appBarFinalDiv = appBarFinalDiv.length >= 1 ? appBarFinalDiv[0] : null; - - var children = this.appBarEl.children; - var length = children.length; - for (var i = 0; i < length; i++) { - var element = children[i]; - if (element === appBarFirstDiv || element === appBarFinalDiv) { - continue; - } else { - _Dispose.disposeSubTree(element); - } - } - }, - handleKeyDown: function _AppBarBaseLayout_handleKeyDown() { - // NOP - }, - commandsUpdated: function _AppBarBaseLayout_commandsUpdated() { - // NOP - }, - beginAnimateCommands: function _AppBarBaseLayout_beginAnimateCommands() { - // The parameters are 3 mutually exclusive arrays of win-command elements contained in this Overlay. - // 1) showCommands[]: All of the HIDDEN win-command elements that ARE scheduled to show. - // 2) hideCommands[]: All of the VISIBLE win-command elements that ARE scheduled to hide. - // 3) otherVisibleCommands[]: All VISIBLE win-command elements that ARE NOT scheduled to hide. - - // NOP - }, - endAnimateCommands: function _AppBarBaseLayout_endAnimateCommands() { - // NOP - }, - scale: function _AppBarBaseLayout_scale() { - // NOP - }, - resize: function _AppBarBaseLayout_resize() { - // NOP - }, - positionChanging: function _AppBarBaseLayout_positionChanging(fromPosition, toPosition) { - // NOP - return Promise.wrap(); - }, - setFocusOnShow: function _AppBarBaseLayout_setFocusOnShow() { - this.appBarEl.winControl._setFocusToAppBar(); - } - }); - return _AppBarBaseLayout; - }), - }); - - // AppBar will use this when AppBar.layout property is set to "commands" - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - _AppBarCommandsLayout: _Base.Namespace._lazy(function () { - var layoutClassName = _Constants.commandLayoutClass; - var layoutType = _Constants.appBarLayoutCommands; - - var _AppBarCommandsLayout = _Base.Class.derive(exports._AppBarBaseLayout, function _AppBarCommandsLayout_ctor(appBarEl) { - exports._AppBarBaseLayout.call(this, appBarEl, { _className: layoutClassName, _type: layoutType }); - this._commandLayoutsInit(appBarEl); - }, { - commandsInOrder: { - get: function _AppBarCommandsLayout_get_commandsInOrder() { - return this._originalCommands.filter(function (command) { - // Make sure the element is still in the AppBar. - return this.appBarEl.contains(command.element); - }, this); - } - }, - layout: function _AppBarCommandsLayout_layout(commands) { - // Insert commands and other layout specific DOM into the AppBar element. - - // Empty our tree. - _ElementUtilities.empty(this._primaryCommands); - _ElementUtilities.empty(this._secondaryCommands); - - // Keep track of the order we receive the commands in. - this._originalCommands = []; - - // Layout commands - for (var i = 0, len = commands.length; i < len; i++) { - var command = this.sanitizeCommand(commands[i]); - - this._originalCommands.push(command); - - if ("primary" === command.section || "global" === command.section) { - this._primaryCommands.appendChild(command._element); - } else { - this._secondaryCommands.appendChild(command._element); - } - } - - // Append layout containers to AppBar element. - // Secondary Commands should come first in Tab Order. - this.appBarEl.appendChild(this._secondaryCommands); - this.appBarEl.appendChild(this._primaryCommands); - - - // Need to measure all content commands after they have been added to the AppBar to make sure we allow - // user defined CSS rules based on the ancestor of the content command to take affect. - this._needToMeasureNewCommands = true; - - // In case this is called from the constructor before the AppBar element has been appended to the DOM, - // we schedule the initial scaling of commands, with the expectation that the element will be added - // synchronously, in the same block of code that called the constructor. - Scheduler.schedule(function () { - if (this._needToMeasureNewCommands && !this._disposed) { - this.scale(); - } - }.bind(this), Scheduler.Priority.idle, this, "WinJS._commandLayoutsMixin._scaleNewCommands"); - - }, - disposeChildren: function _AppBarCommandsLayout_disposeChildren() { - _Dispose.disposeSubTree(this._primaryCommands); - _Dispose.disposeSubTree(this._secondaryCommands); - }, - handleKeyDown: function _AppBarCommandsLayout_handleKeyDown(event) { - var Key = _ElementUtilities.Key; - - if (_ElementUtilities._matchesSelector(event.target, ".win-interactive, .win-interactive *")) { - return; // Ignore left, right, home & end keys if focused element has win-interactive class. - } - var rtl = _Global.getComputedStyle(this.appBarEl).direction === "rtl"; - var leftKey = rtl ? Key.rightArrow : Key.leftArrow; - var rightKey = rtl ? Key.leftArrow : Key.rightArrow; - - if (event.keyCode === leftKey || event.keyCode === rightKey || event.keyCode === Key.home || event.keyCode === Key.end) { - - var globalCommandHasFocus = this._primaryCommands.contains(_Global.document.activeElement); - var focusableCommands = this._getFocusableCommandsInLogicalOrder(globalCommandHasFocus); - var targetCommand; - - if (focusableCommands.length) { - switch (event.keyCode) { - case leftKey: - // Arrowing past the last command wraps back around to the first command. - var index = Math.max(-1, focusableCommands.focusedIndex - 1) + focusableCommands.length; - targetCommand = focusableCommands[index % focusableCommands.length].winControl.lastElementFocus; - break; - - case rightKey: - // Arrowing previous to the first command wraps back around to the last command. - var index = focusableCommands.focusedIndex + 1 + focusableCommands.length; - targetCommand = focusableCommands[index % focusableCommands.length].winControl.firstElementFocus; - break; - - case Key.home: - var index = 0; - targetCommand = focusableCommands[index].winControl.firstElementFocus; - break; - - case Key.end: - var index = focusableCommands.length - 1; - targetCommand = focusableCommands[index].winControl.lastElementFocus; - break; - } - } - - if (targetCommand && targetCommand !== _Global.document.activeElement) { - targetCommand.focus(); - // Prevent default so that the browser doesn't also evaluate the keydown event on the newly focused element. - event.preventDefault(); - } - } - }, - commandsUpdated: function _AppBarCommandsLayout_commandsUpdated(newSetOfVisibleCommands) { - // Whenever new commands are set or existing commands are hiding/showing in the AppBar, this - // function is called to update the cached width measurement of all visible AppBarCommands. - - var visibleCommands = (newSetOfVisibleCommands) ? newSetOfVisibleCommands : this.commandsInOrder.filter(function (command) { - return !command.hidden; - }); - this._fullSizeWidthOfLastKnownVisibleCommands = this._getWidthOfFullSizeCommands(visibleCommands); - }, - beginAnimateCommands: function _AppBarCommandsLayout_beginAnimateCommands(showCommands, hideCommands, otherVisibleCommands) { - // The parameters are 3 mutually exclusive arrays of win-command elements contained in this Overlay. - // 1) showCommands[]: All of the HIDDEN win-command elements that ARE scheduled to show. - // 2) hideCommands[]: All of the VISIBLE win-command elements that ARE scheduled to hide. - // 3) otherVisibleCommands[]: All VISIBLE win-command elements that ARE NOT scheduled to hide. - - this._scaleAfterAnimations = false; - - // Determine if the overall width of visible commands in the primary row will be increasing OR decreasing. - var changeInWidth = this._getWidthOfFullSizeCommands(showCommands) - this._getWidthOfFullSizeCommands(hideCommands); - if (changeInWidth > 0) { - // Width of contents is going to increase, update our command counts now, to what they will be after we complete the animations. - var visibleCommandsAfterAnimations = otherVisibleCommands.concat(showCommands); - this.commandsUpdated(visibleCommandsAfterAnimations); - // Make sure we will have enough room to fit everything on a single row. - this.scale(); - } else if (changeInWidth < 0) { - // Width of contents is going to decrease. Once animations are complete, check if - // there is enough available space to make the remaining commands full size. - this._scaleAfterAnimations = true; - } - }, - endAnimateCommands: function _AppBarCommandsLayout_endAnimateCommands() { - if (this._scaleAfterAnimations) { - this.commandsUpdated(); - this.scale(); - } - }, - resize: function _AppBarCommandsLayout_resize() { - if (!this._disposed) { - // Check for horizontal window resizes. - this._appBarTotalKnownWidth = null; - if (this.appBarEl.winControl.opened) { - this.scale(); - } - } - }, - disconnect: function _AppBarCommandsLayout_disconnect() { - exports._AppBarBaseLayout.prototype.disconnect.call(this); - }, - _getWidthOfFullSizeCommands: function _AppBarCommandsLayout_getWidthOfFullSizeCommands(commands) { - // Commands layout puts primary commands and secondary commands into the primary row. - // Return the total width of all visible primary and secondary commands as if they were full-size. - - // Perform any pending measurements on "content" type AppBarCommands. - if (this._needToMeasureNewCommands) { - this._measureContentCommands(); - } - var accumulatedWidth = 0; - var separatorsCount = 0; - var buttonsCount = 0; - - if (!commands) { - // Return the cached full size width of the last known visible commands in the AppBar. - return this._fullSizeWidthOfLastKnownVisibleCommands; - } else { - // Return the width of the specified commands. - var command; - for (var i = 0, len = commands.length; i < len; i++) { - command = commands[i].winControl || commands[i]; - if (command._type === _Constants.typeSeparator) { - separatorsCount++; - } else if (command._type !== _Constants.typeContent) { - // button, toggle, and flyout types all have the same width. - buttonsCount++; - } else { - accumulatedWidth += command._fullSizeWidth; - } - } - } - return accumulatedWidth += (separatorsCount * _Constants.separatorWidth) + (buttonsCount * _Constants.buttonWidth); - }, - _getFocusableCommandsInLogicalOrder: function _AppBarCommandsLayout_getCommandsInLogicalOrder() { - // Function returns an array of all the contained AppBarCommands which are reachable by left/right arrows. - - var secondaryCommands = this._secondaryCommands.children, - primaryCommands = this._primaryCommands.children, - focusedIndex = -1; - - var getFocusableCommandsHelper = function (commandsInReach) { - var focusableCommands = []; - for (var i = 0, len = commandsInReach.length; i < len; i++) { - var element = commandsInReach[i]; - if (_ElementUtilities.hasClass(element, _Constants.appBarCommandClass) && element.winControl) { - var containsFocus = element.contains(_Global.document.activeElement); - // With the inclusion of content type commands, it may be possible to tab to elements in AppBarCommands that are not reachable by arrow keys. - // Regardless, when an AppBarCommand contains the element with focus, we just include the whole command so that we can determine which - // commands are adjacent to it when looking for the next focus destination. - if (element.winControl._isFocusable() || containsFocus) { - focusableCommands.push(element); - if (containsFocus) { - focusedIndex = focusableCommands.length - 1; - } - } - } - } - return focusableCommands; - }; - - // Determines which set of commands the user could potentially reach through Home, End, and arrow keys. - // All commands in the commands layout AppBar, from left to right are in reach. Secondary (previously known as Selection) - // then Primary (previously known as Global). - var commandsInReach = Array.prototype.slice.call(secondaryCommands).concat(Array.prototype.slice.call(primaryCommands)); - - var focusableCommands = getFocusableCommandsHelper(commandsInReach); - focusableCommands.focusedIndex = focusedIndex; - return focusableCommands; - }, - _commandLayoutsInit: function _AppBarCommandsLayout_commandLayoutsInit() { - // Create layout infrastructure - this._primaryCommands = _Global.document.createElement("DIV"); - this._secondaryCommands = _Global.document.createElement("DIV"); - _ElementUtilities.addClass(this._primaryCommands, _Constants.primaryCommandsClass); - _ElementUtilities.addClass(this._secondaryCommands, _Constants.secondaryCommandsClass); - }, - _scaleHelper: function _AppBarCommandsLayout_scaleHelper() { - // This exists as a single line function so that unit tests can - // overwrite it since they can't resize the WWA window. - - // It is expected that AppBar is an immediate child of the and will have 100% width. - // We measure the clientWidth of the documentElement so that we can scale the AppBar lazily - // even while its element is display: 'none' - var extraPadding = this.appBarEl.winControl.closedDisplayMode === "minimal" ? _Constants.appBarInvokeButtonWidth : 0; - return _Global.document.documentElement.clientWidth - extraPadding; - }, - _measureContentCommands: function _AppBarCommandsLayout_measureContentCommands() { - // AppBar measures the width of content commands when they are first added - // and then caches that value to avoid additional layouts in the future. - - // Can't measure unless We're in the document body - if (_Global.document.body.contains(this.appBarEl)) { - this._needToMeasureNewCommands = false; - - var hadHiddenClass = _ElementUtilities.hasClass(this.appBarEl, "win-navbar-closed"); - _ElementUtilities.removeClass(this.appBarEl, "win-navbar-closed"); - - // Make sure AppBar and children have width dimensions. - var prevAppBarDisplay = this.appBarEl.style.display; - this.appBarEl.style.display = ""; - var prevCommandDisplay; - - var contentElements = this.appBarEl.querySelectorAll("div." + _Constants.appBarCommandClass); - var element; - for (var i = 0, len = contentElements.length; i < len; i++) { - element = contentElements[i]; - if (element.winControl && element.winControl._type === _Constants.typeContent) { - // Make sure command has width dimensions before we measure. - prevCommandDisplay = element.style.display; - element.style.display = ""; - element.winControl._fullSizeWidth = _ElementUtilities.getTotalWidth(element) || 0; - element.style.display = prevCommandDisplay; - } - } - - // Restore state to AppBar. - this.appBarEl.style.display = prevAppBarDisplay; - if (hadHiddenClass) { - _ElementUtilities.addClass(this.appBarEl, "win-navbar-closed"); - } - - this.commandsUpdated(); - } - }, - }); - return _AppBarCommandsLayout; - }), - }); - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - _AppBarMenuLayout: _Base.Namespace._lazy(function () { - var layoutClassName = _Constants.menuLayoutClass; - var layoutType = _Constants.appBarLayoutMenu; - - // - // Resize animation - // The resize animation requires 2 animations to run simultaneously in sync with each other. It's implemented - // without PVL because PVL doesn't provide a way to guarantee that 2 animations will start at the same time. - // - var transformNames = _BaseUtils._browserStyleEquivalents["transform"]; - function transformWithTransition(element, transition) { - // transition's properties: - // - duration: Number representing the duration of the animation in milliseconds. - // - timing: String representing the CSS timing function that controls the progress of the animation. - // - to: The value of *element*'s transform property after the animation. - var duration = transition.duration * _TransitionAnimation._animationFactor; - var transitionProperty = _BaseUtils._browserStyleEquivalents["transition"].scriptName; - element.style[transitionProperty] = duration + "ms " + transformNames.cssName + " " + transition.timing; - element.style[transformNames.scriptName] = transition.to; - - var finish; - return new Promise(function (c) { - var onTransitionEnd = function (eventObject) { - if (eventObject.target === element && eventObject.propertyName === transformNames.cssName) { - finish(); - } - }; - - var didFinish = false; - finish = function () { - if (!didFinish) { - _Global.clearTimeout(timeoutId); - element.removeEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd); - element.style[transitionProperty] = ""; - didFinish = true; - } - c(); - }; - - // Watch dog timeout - var timeoutId = _Global.setTimeout(function () { - timeoutId = _Global.setTimeout(finish, duration); - }, 50); - - element.addEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd); - }, function () { - finish(); // On cancelation, complete the promise successfully to match PVL - }); - } - // See resizeTransition's comment for documentation on *args*. - function growTransition(elementClipper, element, args) { - var diff = args.anchorTrailingEdge ? args.to.total - args.from.total : args.from.total - args.to.total; - var translate = args.dimension === "width" ? "translateX" : "translateY"; - var size = args.dimension; - var duration = args.duration || 367; - var timing = args.timing || "cubic-bezier(0.1, 0.9, 0.2, 1)"; - - // Set up - elementClipper.style[size] = args.to.total + "px"; - elementClipper.style[transformNames.scriptName] = translate + "(" + diff + "px)"; - element.style[size] = args.to.content + "px"; - element.style[transformNames.scriptName] = translate + "(" + -diff + "px)"; - - // Resolve styles - _Global.getComputedStyle(elementClipper).opacity; - _Global.getComputedStyle(element).opacity; - - // Animate - var transition = { - duration: duration, - timing: timing, - to: "" - }; - return Promise.join([ - transformWithTransition(elementClipper, transition), - transformWithTransition(element, transition) - ]); - } - // See resizeTransition's comment for documentation on *args*. - function shrinkTransition(elementClipper, element, args) { - var diff = args.anchorTrailingEdge ? args.from.total - args.to.total : args.to.total - args.from.total; - var translate = args.dimension === "width" ? "translateX" : "translateY"; - var duration = args.duration || 367; - var timing = args.timing || "cubic-bezier(0.1, 0.9, 0.2, 1)"; - - // Set up - elementClipper.style[transformNames.scriptName] = ""; - element.style[transformNames.scriptName] = ""; - - // Resolve styles - _Global.getComputedStyle(elementClipper).opacity; - _Global.getComputedStyle(element).opacity; - - // Animate - var transition = { - duration: duration, - timing: timing - }; - var clipperTransition = _BaseUtils._merge(transition, { to: translate + "(" + diff + "px)" }); - var elementTransition = _BaseUtils._merge(transition, { to: translate + "(" + -diff + "px)" }); - return Promise.join([ - transformWithTransition(elementClipper, clipperTransition), - transformWithTransition(element, elementTransition) - ]); - } - // Plays an animation which makes an element look like it is resizing in 1 dimension. Arguments: - // - elementClipper: The parent of *element*. It shouldn't have any margin, border, or padding and its - // size should match element's size. Its purpose is to clip *element* during the animation to give - // it the illusion that it is resizing. - // - element: The element that should look like it's resizing. - // - args: An object with the following required properties: - // - from: An object representing the old width/height of the element. - // - to: An object representing the new width/height of the element. - // from/to are objects of the form { content: number; total: number; }. "content" is the - // width/height of *element*'s content box (e.g. getContentWidth). "total" is the width/height - // of *element*'s margin box (e.g. getTotalWidth). - // - duration: The CSS transition duration property. - // - timing: The CSS transition timing property. - // - dimension: The dimension on which *element* is resizing. Either "width" or "height". - // - anchorTrailingEdge: During the resize animation, one edge will move and the other edge will - // remain where it is. This flag specifies which edge is anchored (i.e. won't move). - // - function resizeTransition(elementClipper, element, args) { - if (args.to.total > args.from.total) { - return growTransition(elementClipper, element, args); - } else if (args.to.total < args.from.total) { - return shrinkTransition(elementClipper, element, args); - } else { - return Promise.as(); - } - } - - var _AppBarMenuLayout = _Base.Class.derive(exports._AppBarBaseLayout, function _AppBarMenuLayout_ctor(appBarEl) { - exports._AppBarBaseLayout.call(this, appBarEl, { _className: layoutClassName, _type: layoutType }); - this._tranformNames = _BaseUtils._browserStyleEquivalents["transform"]; - this._animationCompleteBound = this._animationComplete.bind(this); - this._positionToolBarBound = this._positionToolBar.bind(this); - }, { - commandsInOrder: { - get: function _AppBarMenuLayout_get_commandsInOrder() { - return this._originalCommands; - } - }, - layout: function _AppBarMenuLayout_layout(commands) { - this._writeProfilerMark("layout,info"); - - commands = commands || []; - this._originalCommands = []; - - var that = this; - commands.forEach(function (command) { - that._originalCommands.push(that.sanitizeCommand(command)); - }); - this._displayedCommands = this._originalCommands.slice(0); - - if (this._menu) { - _ElementUtilities.empty(this._menu); - } else { - this._menu = _Global.document.createElement("div"); - _ElementUtilities.addClass(this._menu, _Constants.menuContainerClass); - } - this.appBarEl.appendChild(this._menu); - - this._toolbarEl = _Global.document.createElement("div"); - this._menu.appendChild(this._toolbarEl); - - this._createToolBar(commands); - }, - - showCommands: function _AppBarMenuLayout_showCommands(commands) { - var elements = this._getCommandsElements(commands); - var data = []; - var newDisplayedCommands = []; - var that = this; - this._originalCommands.forEach(function (command) { - if (elements.indexOf(command.element) >= 0 || that._displayedCommands.indexOf(command) >= 0) { - newDisplayedCommands.push(command); - data.push(command); - } - }); - this._displayedCommands = newDisplayedCommands; - this._updateData(data); - }, - - showOnlyCommands: function _AppBarMenuLayout_showOnlyCommands(commands) { - this._displayedCommands = []; - this.showCommands(commands); - }, - - hideCommands: function _AppBarMenuLayout_hideCommands(commands) { - var elements = this._getCommandsElements(commands); - var data = []; - var newDisplayedCommands = []; - var that = this; - this._originalCommands.forEach(function (command) { - if (elements.indexOf(command.element) === -1 && that._displayedCommands.indexOf(command) >= 0) { - newDisplayedCommands.push(command); - data.push(command); - } - }); - this._displayedCommands = newDisplayedCommands; - this._updateData(data); - }, - - connect: function _AppBarMenuLayout_connect(appBarEl) { - this._writeProfilerMark("connect,info"); - - exports._AppBarBaseLayout.prototype.connect.call(this, appBarEl); - this._id = _ElementUtilities._uniqueID(appBarEl); - }, - - resize: function _AppBarMenuLayout_resize() { - this._writeProfilerMark("resize,info"); - - if (this._initialized) { - this._forceLayoutPending = true; - } - }, - - positionChanging: function _AppBarMenuLayout_positionChanging(fromPosition, toPosition) { - this._writeProfilerMark("positionChanging from:" + fromPosition + " to: " + toPosition + ",info"); - - this._animationPromise = this._animationPromise || Promise.wrap(); - - if (this._animating) { - this._animationPromise.cancel(); - } - - this._animating = true; - if (toPosition === "shown" || (fromPosition !== "shown" && toPosition === "compact")) { - this._positionToolBar(); - this._animationPromise = this._animateToolBarEntrance(); - } else { - if (fromPosition === "minimal" || fromPosition === "compact" || fromPosition === "hidden") { - this._animationPromise = Promise.wrap(); - } else { - this._animationPromise = this._animateToolBarExit(); - } - } - this._animationPromise.then(this._animationCompleteBound, this._animationCompleteBound); - return this._animationPromise; - }, - - disposeChildren: function _AppBarMenuLayout_disposeChildren() { - this._writeProfilerMark("disposeChildren,info"); - - if (this._toolbar) { - _Dispose.disposeSubTree(this._toolbarEl); - } - this._originalCommands = []; - this._displayedCommands = []; - }, - - setFocusOnShow: function _AppBarMenuLayout_setFocusOnShow() { - // Make sure the menu (used for clipping during the resize animation) - // doesn't scroll when we give focus to the AppBar. - this.appBarEl.winControl._setFocusToAppBar(true, this._menu); - }, - - _updateData: function _AppBarMenuLayout_updateData(data) { - var hadHiddenClass = _ElementUtilities.hasClass(this.appBarEl, "win-navbar-closed"); - var hadShownClass = _ElementUtilities.hasClass(this.appBarEl, "win-navbar-opened"); - _ElementUtilities.removeClass(this.appBarEl, "win-navbar-closed"); - - // Make sure AppBar and children have width dimensions. - var prevAppBarDisplay = this.appBarEl.style.display; - this.appBarEl.style.display = ""; - - - this._toolbar.data = new BindingList.List(data); - if (hadHiddenClass) { - this._positionToolBar(); - } - - // Restore state to AppBar. - this.appBarEl.style.display = prevAppBarDisplay; - if (hadHiddenClass) { - _ElementUtilities.addClass(this.appBarEl, "win-navbar-closed"); - } - - if (hadShownClass) { - this._positionToolBar(); - this._animateToolBarEntrance(); - } - }, - - _getCommandsElements: function _AppBarMenuLayout_getCommandsElements(commands) { - if (!commands) { - return []; - } - - if (typeof commands === "string" || !commands || !commands.length) { - commands = [commands]; - } - - var elements = []; - for (var i = 0, len = commands.length; i < len; i++) { - if (commands[i]) { - if (typeof commands[i] === "string") { - var element = _Global.document.getElementById(commands[i]); - if (element) { - elements.push(element); - } else { - // Check in the list we are tracking, since it might not be in the DOM yet - for (var j = 0, len2 = this._originalCommands.length; j < len2; j++) { - var element = this._originalCommands[j].element; - if (element.id === commands[i]) { - elements.push(element); - } - } - } - } else if (commands[i].element) { - elements.push(commands[i].element); - } else { - elements.push(commands[i]); - } - } - } - - return elements; - }, - - _animationComplete: function _AppBarMenuLayout_animationComplete() { - if (!this._disposed) { - this._animating = false; - } - }, - - _createToolBar: function _AppBarMenuLayout_createToolBar(commands) { - this._writeProfilerMark("_createToolBar,info"); - - var hadHiddenClass = _ElementUtilities.hasClass(this.appBarEl, "win-navbar-closed"); - _ElementUtilities.removeClass(this.appBarEl, "win-navbar-closed"); - - // Make sure AppBar and children have width dimensions. - var prevAppBarDisplay = this.appBarEl.style.display; - this.appBarEl.style.display = ""; - - this._toolbar = new ToolBar.ToolBar(this._toolbarEl, { - data: new BindingList.List(this._originalCommands), - shownDisplayMode: 'full', - }); - - var that = this; - this._appbarInvokeButton = this.appBarEl.querySelector("." + _Constants.invokeButtonClass); - this._overflowButton = this._toolbarEl.querySelector("." + _ToolBarConstants.overflowButtonCssClass); - this._overflowButton.addEventListener("click", function () { - that._appbarInvokeButton.click(); - }); - - this._positionToolBar(); - - // Restore state to AppBar. - this.appBarEl.style.display = prevAppBarDisplay; - if (hadHiddenClass) { - _ElementUtilities.addClass(this.appBarEl, "win-navbar-closed"); - } - }, - - _positionToolBar: function _AppBarMenuLayout_positionToolBar() { - if (!this._disposed) { - this._writeProfilerMark("_positionToolBar,info"); - this._initialized = true; - } - }, - - _animateToolBarEntrance: function _AppBarMenuLayout_animateToolBarEntrance() { - this._writeProfilerMark("_animateToolBarEntrance,info"); - - if (this._forceLayoutPending) { - this._forceLayoutPending = false; - this._toolbar.forceLayout(); - this._positionToolBar(); - } - var heightVisible = this._isMinimal() ? 0 : this.appBarEl.offsetHeight; - if (this._isBottom()) { - // Bottom AppBar Animation - var offsetTop = this._menu.offsetHeight - heightVisible; - return this._executeTranslate(this._menu, "translateY(" + -offsetTop + "px)"); - } else { - // Top AppBar Animation - return resizeTransition(this._menu, this._toolbarEl, { - from: { content: heightVisible, total: heightVisible }, - to: { content: this._menu.offsetHeight, total: this._menu.offsetHeight }, - dimension: "height", - duration: 400, - timing: "ease-in", - }); - } - }, - - _animateToolBarExit: function _AppBarMenuLayout_animateToolBarExit() { - this._writeProfilerMark("_animateToolBarExit,info"); - - var heightVisible = this._isMinimal() ? 0 : this.appBarEl.offsetHeight; - if (this._isBottom()) { - return this._executeTranslate(this._menu, "none"); - } else { - // Top AppBar Animation - return resizeTransition(this._menu, this._toolbarEl, { - from: { content: this._menu.offsetHeight, total: this._menu.offsetHeight }, - to: { content: heightVisible, total: heightVisible }, - dimension: "height", - duration: 400, - timing: "ease-in", - }); - } - }, - - _executeTranslate: function _AppBarMenuLayout_executeTranslate(element, value) { - return _TransitionAnimation.executeTransition(element, - { - property: this._tranformNames.cssName, - delay: 0, - duration: 400, - timing: "ease-in", - to: value - }); - }, - - _isMinimal: function _AppBarMenuLayout_isMinimal() { - return this.appBarEl.winControl.closedDisplayMode === "minimal"; - }, - - _isBottom: function _AppBarMenuLayout_isBottom() { - return this.appBarEl.winControl.placement === "bottom"; - }, - - _writeProfilerMark: function _AppBarMenuLayout_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI._AppBarMenuLayout:" + this._id + ":" + text); - } - }); - - return _AppBarMenuLayout; - }), - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -// _LegacyAppBar -/// appbar,appBars,Flyout,Flyouts,iframe,Statics,unfocus,WinJS -define('WinJS/Controls/_LegacyAppBar',[ - 'exports', - '../Core/_Global', - '../Core/_WinRT', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_ErrorFromName', - '../Core/_Events', - '../Core/_Resources', - '../Core/_WriteProfilerMark', - '../Animations', - '../Promise', - '../Scheduler', - '../_LightDismissService', - '../Utilities/_Control', - '../Utilities/_Dispose', - '../Utilities/_ElementUtilities', - '../Utilities/_Hoverable', - '../Utilities/_KeyboardBehavior', - './_LegacyAppBar/_Constants', - './_LegacyAppBar/_Layouts', - './AppBar/_Command', - './AppBar/_Icon', - './Flyout/_Overlay', - '../Application' -], function appBarInit(exports, _Global, _WinRT, _Base, _BaseUtils, _ErrorFromName, _Events, _Resources, _WriteProfilerMark, Animations, Promise, Scheduler, _LightDismissService, _Control, _Dispose, _ElementUtilities, _Hoverable, _KeyboardBehavior, _Constants, _Layouts, _Command, _Icon, _Overlay, Application) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// - /// Represents an application toolbar for display commands. - /// - /// - /// - /// - /// - /// - /// ]]> - /// Raised just before showing the _LegacyAppBar. - /// Raised immediately after the _LegacyAppBar is fully shown. - /// Raised just before hiding the _LegacyAppBar. - /// Raised immediately after the _LegacyAppBar is fully hidden. - /// The _LegacyAppBar control itself. - /// Style for a custom layout _LegacyAppBar. - /// - /// - _LegacyAppBar: _Base.Namespace._lazy(function () { - var EVENTS = { - beforeOpen: "beforeopen", - afterOpen: "afteropen", - beforeClose: "beforeclose", - afterClose: "afterclose", - }; - - var createEvent = _Events._createEventProperty; - - // Enum of known constant pixel values for display modes. - var knownVisibleHeights = { - none: 0, - hidden: 0, - minimal: 25, - compact: 48 - }; - - // Maps each notion of a display modes to the corresponding visible position - var displayModeVisiblePositions = { - none: "hidden", - hidden: "hidden", - minimal: "minimal", - shown: "shown", - compact: "compact" - }; - - // Enum of closedDisplayMode constants - var closedDisplayModes = { - none: "none", - minimal: "minimal", - compact: "compact" - }; - - // Constants shown/hidden states - var appbarShownState = "shown", - appbarHiddenState = "hidden"; - - // Hook into event - var globalEventsInitialized = false; - - function _allManipulationChanged(event) { - var elements = _Global.document.querySelectorAll("." + _Constants.appBarClass); - if (elements) { - var len = elements.length; - for (var i = 0; i < len; i++) { - var element = elements[i]; - var appbar = element.winControl; - if (appbar && !element.disabled) { - appbar._manipulationChanged(event); - } - } - } - } - - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/appBarAriaLabel").value; }, - get requiresCommands() { return "Invalid argument: commands must not be empty"; }, - get cannotChangePlacementWhenVisible() { return "Invalid argument: The placement property cannot be set when the AppBar is visible, call hide() first"; }, - get cannotChangeLayoutWhenVisible() { return "Invalid argument: The layout property cannot be set when the AppBar is visible, call hide() first"; } - }; - - var _LegacyAppBar = _Base.Class.derive(_Overlay._Overlay, function _LegacyAppBar_ctor(element, options) { - /// - /// - /// Creates a new _LegacyAppBar control. - /// - /// - /// The DOM element that will host the control. - /// - /// - /// The set of properties and values to apply to the new _LegacyAppBar control. - /// - /// - /// The new _LegacyAppBar control. - /// - /// - - this._initializing = true; - - // Simplify checking later - options = options || {}; - - // Make sure there's an element - this._element = element || _Global.document.createElement("div"); - this._id = this._element.id || _ElementUtilities._uniqueID(this._element); - this._writeProfilerMark("constructor,StartTM"); - - // Attach our css class. - _ElementUtilities.addClass(this._element, _Constants.appBarClass); - - var that = this; - this._dismissable = new _LightDismissService.LightDismissableElement({ - element: this._element, - tabIndex: this._element.hasAttribute("tabIndex") ? this._element.tabIndex : -1, - onLightDismiss: function () { - that.close(); - }, - onTakeFocus: function (useSetActive) { - if (!that._dismissable.restoreFocus()) { - that._layoutImpl.setFocusOnShow(); - } - }, - }); - - // Make sure we have an ARIA role - var role = this._element.getAttribute("role"); - if (!role) { - this._element.setAttribute("role", "menubar"); - } - var label = this._element.getAttribute("aria-label"); - if (!label) { - this._element.setAttribute("aria-label", strings.ariaLabel); - } - - // Call the _Overlay constructor helper to finish setting up our element. - // Don't pass constructor options, _LegacyAppBar needs to set those itself specific order. - this._baseOverlayConstructor(this._element); - - // Start off hidden - this._lastPositionVisited = displayModeVisiblePositions.none; - _ElementUtilities.addClass(this._element, _Constants.hiddenClass); - - // Add Invoke button. - this._invokeButton = _Global.document.createElement("button"); - this._invokeButton.tabIndex = 0; - this._invokeButton.setAttribute("type", "button"); - this._invokeButton.innerHTML = ""; - _ElementUtilities.addClass(this._invokeButton, _Constants.invokeButtonClass); - this._element.appendChild(this._invokeButton); - this._invokeButton.addEventListener("click", function () { - if (that.opened) { - that._hide(); - } else { - that._show(); - } - }, false); - - // Run layout setter immediately. We need to know our layout in order to correctly - // position any commands that may be getting set through the constructor. - this._layout = _Constants.appBarLayoutCustom; - delete options._layout; - - // Need to set placement before closedDisplayMode, closedDisplayMode sets our starting position, which is dependant on placement. - this.placement = options.placement || _Constants.appBarPlacementBottom; - this.closedDisplayMode = options.closedDisplayMode || closedDisplayModes.compact; - - _Control.setOptions(this, options); - - var commandsUpdatedBound = this._commandsUpdated.bind(this); - this._element.addEventListener(_Constants.commandVisibilityChanged, function (ev) { - if (that._disposed) { - return; - } - if (that.opened) { - ev.preventDefault(); - } - commandsUpdatedBound(); - }); - - this._initializing = false; - - this._setFocusToAppBarBound = this._setFocusToAppBar.bind(this); - - // Handle key down (left & right) - this._element.addEventListener("keydown", this._handleKeyDown.bind(this), false); - - // Attach global event handlers - if (!globalEventsInitialized) { - // Need to know if the IHM is done scrolling - _Global.document.addEventListener("MSManipulationStateChanged", _allManipulationChanged, false); - - globalEventsInitialized = true; - } - - if (this.closedDisplayMode === closedDisplayModes.none && this.layout === _Constants.appBarLayoutCommands) { - // Remove the commands layout _LegacyAppBar from the layout tree at this point so we don't cause unnecessary layout costs whenever - // the window resizes or when CSS changes are applied to the commands layout _LegacyAppBar's parent element. - this._element.style.display = "none"; - } - - this._winKeyboard = new _KeyboardBehavior._WinKeyboard(this._element); - - this._writeProfilerMark("constructor,StopTM"); - - return this; - }, { - // Public Properties - - /// The placement of the _LegacyAppBar on the display. Values are "top" or "bottom". - placement: { - get: function _LegacyAppBar_get_placement() { - return this._placement; - }, - set: function _LegacyAppBar_set_placement(value) { - // In designer we may have to move it - var wasShown = false; - if (_WinRT.Windows.ApplicationModel.DesignMode.designModeEnabled) { - this._hide(); - wasShown = true; - } - - if (this.opened) { - throw new _ErrorFromName("WinJS.UI._LegacyAppBar.CannotChangePlacementWhenVisible", strings.cannotChangePlacementWhenVisible); - } - - // Set placement, coerce invalid values to 'bottom' - this._placement = (value === _Constants.appBarPlacementTop) ? _Constants.appBarPlacementTop : _Constants.appBarPlacementBottom; - - // Clean up win-top, win-bottom styles - if (this._placement === _Constants.appBarPlacementTop) { - _ElementUtilities.addClass(this._element, _Constants.topClass); - _ElementUtilities.removeClass(this._element, _Constants.bottomClass); - } else if (this._placement === _Constants.appBarPlacementBottom) { - _ElementUtilities.removeClass(this._element, _Constants.topClass); - _ElementUtilities.addClass(this._element, _Constants.bottomClass); - } - - // Update our position on screen. - this._ensurePosition(); - if (wasShown) { - // Show again if we hid ourselves for the designer - this._show(); - } - } - }, - - _layout: { - get: function _LegacyAppBar_get_layout() { - return this._layoutImpl.type; - }, - set: function (layout) { - if (layout !== _Constants.appBarLayoutCommands && - layout !== _Constants.appBarLayoutCustom && - layout !== _Constants.appBarLayoutMenu) { - } - - // In designer we may have to redraw it - var wasShown = false; - if (_WinRT.Windows.ApplicationModel.DesignMode.designModeEnabled) { - this._hide(); - wasShown = true; - } - - if (this.opened) { - throw new _ErrorFromName("WinJS.UI._LegacyAppBar.CannotChangeLayoutWhenVisible", strings.cannotChangeLayoutWhenVisible); - } - - var commands; - if (!this._initializing) { - // Gather commands in preparation for hand off to new layout. - // We expect prev layout to return commands in the order they were set in, - // not necessarily the current DOM order the layout is using. - commands = this._layoutImpl.commandsInOrder; - this._layoutImpl.disconnect(); - } - - // Set layout - if (layout === _Constants.appBarLayoutCommands) { - this._layoutImpl = new _Layouts._AppBarCommandsLayout(); - } else if (layout === _Constants.appBarLayoutMenu) { - this._layoutImpl = new _Layouts._AppBarMenuLayout(); - } else { - // Custom layout uses Base _LegacyAppBar Layout class. - this._layoutImpl = new _Layouts._AppBarBaseLayout(); - } - this._layoutImpl.connect(this._element); - - if (commands && commands.length) { - // Reset _LegacyAppBar since layout changed. - this._layoutCommands(commands); - } - - // Show again if we hid ourselves for the designer - if (wasShown) { - this._show(); - } - }, - configurable: true - }, - - /// - /// Sets the AppBarCommands in the _LegacyAppBar. This property accepts an array of AppBarCommand objects. - /// - commands: { - set: function _LegacyAppBar_set_commands(commands) { - // Fail if trying to set when shown - if (this.opened) { - throw new _ErrorFromName("WinJS.UI._LegacyAppBar.CannotChangeCommandsWhenVisible", _Resources._formatString(_Overlay._Overlay.commonstrings.cannotChangeCommandsWhenVisible, "_LegacyAppBar")); - } - - // Dispose old commands before tossing them out. - if (!this._initializing) { - // AppBarCommands defined in markup don't want to be disposed during initialization. - this._disposeChildren(); - } - this._layoutCommands(commands); - } - }, - - _layoutCommands: function _LegacyAppBar_layoutCommands(commands) { - // Function precondition: _LegacyAppBar must not be shown. - - // Empties _LegacyAppBar HTML and repopulates with passed in commands. - _ElementUtilities.empty(this._element); - this._element.appendChild(this._invokeButton); // Keep our Show/Hide button. - - // In case they had only one command to set... - if (!Array.isArray(commands)) { - commands = [commands]; - } - - this._layoutImpl.layout(commands); - }, - - /// - /// Gets/Sets how _LegacyAppBar will display itself while hidden. Values are "none", "minimal" and '"compact". - /// - closedDisplayMode: { - get: function _LegacyAppBar_get_closedDisplayMode() { - return this._closedDisplayMode; - }, - set: function _LegacyAppBar_set_closedDisplayMode(value) { - var oldValue = this._closedDisplayMode; - - if (oldValue !== value) { - - // Determine if the visible position is changing. This can be used to determine if we need to delay updating closedDisplayMode related CSS classes - // to avoid affecting the animation. - var changeVisiblePosition = _ElementUtilities.hasClass(this._element, _Constants.hiddenClass) || _ElementUtilities.hasClass(this._element, _Constants.hidingClass); - - if (value === closedDisplayModes.none) { - this._closedDisplayMode = closedDisplayModes.none; - if (!changeVisiblePosition || !oldValue) { - _ElementUtilities.removeClass(this._element, _Constants.minimalClass); - _ElementUtilities.removeClass(this._element, _Constants.compactClass); - } - } else if (value === closedDisplayModes.minimal) { - this._closedDisplayMode = closedDisplayModes.minimal; - if (!changeVisiblePosition || !oldValue || oldValue === closedDisplayModes.none) { - _ElementUtilities.addClass(this._element, _Constants.minimalClass); - _ElementUtilities.removeClass(this._element, _Constants.compactClass); - } - } else { - // Compact is default fallback. - this._closedDisplayMode = closedDisplayModes.compact; - _ElementUtilities.addClass(this._element, _Constants.compactClass); - _ElementUtilities.removeClass(this._element, _Constants.minimalClass); - } - - // The invoke button has changed the amount of available space in the _LegacyAppBar. Layout might need to scale. - this._layoutImpl.resize(); - - if (changeVisiblePosition) { - // If the value is being set while we are not showing, change to our new position. - this._changeVisiblePosition(displayModeVisiblePositions[this._closedDisplayMode]); - } - } - }, - }, - - /// - opened: { - get: function () { - // Returns true if _LegacyAppBar is not 'hidden'. - return !_ElementUtilities.hasClass(this._element, _Constants.hiddenClass) && - !_ElementUtilities.hasClass(this._element, _Constants.hidingClass) && - this._doNext !== displayModeVisiblePositions.minimal && - this._doNext !== displayModeVisiblePositions.compact && - this._doNext !== displayModeVisiblePositions.none; - }, - set: function (opened) { - var currentlyOpen = this.opened; - if (opened && !currentlyOpen) { - this._show(); - } else if (!opened && currentlyOpen) { - this._hide(); - } - } - }, - - /// - /// Occurs immediately before the control is opened. - /// - onbeforeopen: createEvent(EVENTS.beforeOpen), - - /// - /// Occurs immediately after the control is opened. - /// - onafteropen: createEvent(EVENTS.afterOpen), - - /// - /// Occurs immediately before the control is closed. - /// - onbeforeclose: createEvent(EVENTS.beforeClose), - - /// - /// Occurs immediately after the control is closed. - /// - onafterclose: createEvent(EVENTS.afterClose), - - getCommandById: function (id) { - /// - /// - /// Retrieves the command with the specified ID from this _LegacyAppBar. - /// If more than one command is found, this method returns them all. - /// - /// Id of the command to return. - /// - /// The command found, an array of commands if more than one have the same ID, or null if no command is found. - /// - /// - var commands = this._layoutImpl.commandsInOrder.filter(function (command) { - return command.id === id || command.element.id === id; - }); - - if (commands.length === 1) { - return commands[0]; - } else if (commands.length === 0) { - return null; - } - - return commands; - }, - - showCommands: function (commands) { - /// - /// - /// Show the specified commands of the _LegacyAppBar. - /// - /// - /// An array of the commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - /// - /// - if (!commands) { - throw new _ErrorFromName("WinJS.UI._LegacyAppBar.RequiresCommands", strings.requiresCommands); - } - - this._layoutImpl.showCommands(commands); - }, - - hideCommands: function (commands) { - /// - /// - /// Hides the specified commands of the _LegacyAppBar. - /// - /// Required. Command or Commands to hide, either String, DOM elements, or WinJS objects. - /// - if (!commands) { - throw new _ErrorFromName("WinJS.UI._LegacyAppBar.RequiresCommands", strings.requiresCommands); - } - - this._layoutImpl.hideCommands(commands); - }, - - showOnlyCommands: function (commands) { - /// - /// - /// Show the specified commands, hiding all of the others in the _LegacyAppBar. - /// - /// - /// An array of the commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - /// - /// - if (!commands) { - throw new _ErrorFromName("WinJS.UI._LegacyAppBar.RequiresCommands", strings.requiresCommands); - } - - this._layoutImpl.showOnlyCommands(commands); - }, - - open: function () { - /// - /// - /// Opens the _LegacyAppBar, if closed and not disabled, regardless of other state. - /// - /// - // Just wrap the private one, turning off keyboard invoked flag - this._writeProfilerMark("show,StartTM"); - this._show(); - }, - - _show: function _LegacyAppBar_show() { - - var toPosition = displayModeVisiblePositions.shown; - var showing = null; - - // If we're already shown, we are just going to animate our position, not fire events or manage focus. - if (!this.disabled && (_ElementUtilities.hasClass(this._element, _Constants.hiddenClass) || _ElementUtilities.hasClass(this._element, _Constants.hidingClass))) { - showing = appbarShownState; - } - - this._changeVisiblePosition(toPosition, showing); - - if (showing) { - // Clean up tabbing behavior by making sure first and final divs are correct after showing. - this._updateFirstAndFinalDiv(); - - _LightDismissService.shown(this._dismissable); - } - }, - - close: function () { - /// - /// - /// Closes the _LegacyAppBar. - /// - /// - // Just wrap the private one - this._writeProfilerMark("hide,StartTM"); - this._hide(); - }, - - _hide: function _LegacyAppBar_hide(toPosition) { - - var toPosition = toPosition || displayModeVisiblePositions[this.closedDisplayMode]; - var hiding = null; - - // If were already hidden, we are just going to animate our position, not fire events or manage focus again. - if (!_ElementUtilities.hasClass(this._element, _Constants.hiddenClass) && !_ElementUtilities.hasClass(this._element, _Constants.hidingClass)) { - hiding = appbarHiddenState; - } - - this._changeVisiblePosition(toPosition, hiding); - }, - - _dispose: function _LegacyAppBar_dispose() { - _Dispose.disposeSubTree(this.element); - _LightDismissService.hidden(this._dismissable); - this._layoutImpl.dispose(); - this.disabled = true; - this.close(); - }, - - _disposeChildren: function _LegacyAppBar_disposeChildren() { - // Be purposeful about what we dispose. - this._layoutImpl.disposeChildren(); - }, - - _handleKeyDown: function _LegacyAppBar_handleKeyDown(event) { - // On Left/Right arrow keys, moves focus to previous/next AppbarCommand element. - - // If the current active element isn't an intrinsic part of the _LegacyAppBar, - // Layout might want to handle additional keys. - if (!this._invokeButton.contains(_Global.document.activeElement)) { - this._layoutImpl.handleKeyDown(event); - } - }, - - _visiblePixels: { - get: function () { - // Returns object containing pixel height of each visible position - return { - hidden: knownVisibleHeights.hidden, - minimal: knownVisibleHeights.minimal, - compact: Math.max(this._heightWithoutLabels || 0, knownVisibleHeights.compact), - // Element can change size as content gets added or removed or if it - // experinces style changes. We have to look this up at run time. - shown: this._element.offsetHeight, - }; - } - }, - - _visiblePosition: { - // Returns string value of our nearest, stationary, visible position. - get: function () { - // If we're animating into a new posistion, return the position we're animating into. - if (this._animating && displayModeVisiblePositions[this._element.winAnimating]) { - return this._element.winAnimating; - } else { - return this._lastPositionVisited; - } - } - }, - - _visible: { - // Returns true if our visible position is not completely hidden, else false. - get: function () { - return (this._visiblePosition !== displayModeVisiblePositions.none); - } - }, - - _changeVisiblePosition: function (toPosition, newState) { - /// - /// - /// Changes the visible position of the _LegacyAppBar. - /// - /// - /// Name of the visible position we want to move to. - /// - /// - /// Name of the state we are entering. Values can be "showing", "hiding" or null. - /// If the value is null, then we are not changing states, only changing visible position. - /// - /// - - if ((this._visiblePosition === toPosition && !this._keyboardObscured) || - (this.disabled && toPosition !== displayModeVisiblePositions.disabled)) { - // If we want to go where we already are, or we're disabled, return false. - this._afterPositionChange(null); - } else if (this._animating || this._needToHandleShowingKeyboard || this._needToHandleHidingKeyboard) { - // Only do one thing at a time. If we are already animating, - // or the IHM is animating, schedule this for later. - this._doNext = toPosition; - this._afterPositionChange(null); - } else { - // Begin position changing sequence. - - // Set the animating flag to block any queued position changes until we're done. - this._element.winAnimating = toPosition; - var performAnimation = this._initializing ? false : true; - - // Assume we are animating from the last position visited. - var fromPosition = this._lastPositionVisited; - - // We'll need to measure our element to determine how far we need to animate. - // Make sure we have accurate dimensions. - this._element.style.display = ""; - - // Are we hiding completely, or about to become visible? - var hidingCompletely = (toPosition === displayModeVisiblePositions.hidden); - - if (this._keyboardObscured) { - // We're changing position while covered by the IHM. - if (hidingCompletely) { - // If we're covered by the IHM we already look hidden. - // We can skip our animation and just hide. - performAnimation = false; - } else { - // Some portion of the _LegacyAppBar should be visible to users after its position changes. - - // Un-obscure ourselves and become visible to the user again. - // Need to animate to our desired position as if we were coming up from behind the keyboard. - fromPosition = displayModeVisiblePositions.hidden; - } - this._keyboardObscured = false; - } - - // Fire "before" event if we are changing state. - if (newState === appbarShownState) { - this._beforeShow(); - } else if (newState === appbarHiddenState) { - this._beforeHide(); - } - - // Position our element into the correct "end of animation" position, - // also accounting for any viewport scrolling or soft keyboard positioning. - this._ensurePosition(); - - this._element.style.opacity = 1; - this._element.style.visibility = "visible"; - - this._animationPromise = (performAnimation) ? this._animatePositionChange(fromPosition, toPosition) : Promise.wrap(); - this._animationPromise.then( - function () { this._afterPositionChange(toPosition, newState); }.bind(this), - function () { this._afterPositionChange(toPosition, newState); }.bind(this) - ); - } - }, - - _afterPositionChange: function _LegacyAppBar_afterPositionChange(newPosition, newState) { - // Defines body of work to perform after changing positions. - if (this._disposed) { - return; - } - - if (newPosition) { - - // Update closedDisplayMode related CSS classes, which were delayed from the closedDisplayMode setter to avoid affecting the animation - if (newPosition === displayModeVisiblePositions.minimal) { - _ElementUtilities.addClass(this._element, _Constants.minimalClass); - _ElementUtilities.removeClass(this._element, _Constants.compactClass); - } - - if (newPosition === displayModeVisiblePositions.hidden && this.closedDisplayMode === closedDisplayModes.none) { - _ElementUtilities.removeClass(this._element, _Constants.minimalClass); - _ElementUtilities.removeClass(this._element, _Constants.compactClass); - } - - // Clear animation flag and record having visited this position. - this._element.winAnimating = ""; - this._lastPositionVisited = newPosition; - - if (this._doNext === this._lastPositionVisited) { - this._doNext = ""; - } - - if (newState === appbarHiddenState) { - _LightDismissService.hidden(this._dismissable); - } - - if (newPosition === displayModeVisiblePositions.hidden) { - // Make sure animation is finished. - this._element.style.visibility = "hidden"; - this._element.style.display = "none"; - } - - // Clean up animation transforms. - var transformProperty = _BaseUtils._browserStyleEquivalents["transform"].scriptName; - this._element.style[transformProperty] = ""; - - // Fire "after" event if we changed state. - if (newState === appbarShownState) { - this._afterShow(); - } else if (newState === appbarHiddenState) { - this._afterHide(); - } - - // If we had something queued, do that - Scheduler.schedule(this._checkDoNext, Scheduler.Priority.normal, this, "WinJS.UI._LegacyAppBar._checkDoNext"); - } - - this._afterPositionChangeCallBack(); - }, - - _afterPositionChangeCallBack: function () { - // Leave this blank for unit tests to overwrite. - }, - - _beforeShow: function _LegacyAppBar_beforeShow() { - // In case their event 'beforeopen' event listener is going to manipulate commands, - // first see if there are any queued command animations we can handle while we're still hidden. - if (this._queuedCommandAnimation) { - this._showAndHideFast(this._queuedToShow, this._queuedToHide); - this._queuedToShow = []; - this._queuedToHide = []; - } - - // Make sure everything fits before showing - this._layoutImpl.scale(); - - if (this.closedDisplayMode === closedDisplayModes.compact) { - this._heightWithoutLabels = this._element.offsetHeight; - } - - _ElementUtilities.removeClass(this._element, _Constants.hiddenClass); - _ElementUtilities.addClass(this._element, _Constants.showingClass); - - // Send our "beforeopen" event - this._sendEvent(EVENTS.beforeOpen); - }, - - _afterShow: function _LegacyAppBar_afterShow() { - _ElementUtilities.removeClass(this._element, _Constants.showingClass); - _ElementUtilities.addClass(this._element, _Constants.shownClass); - - // Send our "afteropen" event - this._sendEvent(EVENTS.afterOpen); - this._writeProfilerMark("show,StopTM"); - }, - - _beforeHide: function _LegacyAppBar_beforeHide() { - - _ElementUtilities.removeClass(this._element, _Constants.shownClass); - _ElementUtilities.addClass(this._element, _Constants.hidingClass); - - // Send our "beforeclose" event - this._sendEvent(EVENTS.beforeClose); - }, - - _afterHide: function _LegacyAppBar_afterHide() { - - // In case their 'afterclose' event handler is going to manipulate commands, - // first see if there are any queued command animations we can handle now we're hidden. - if (this._queuedCommandAnimation) { - this._showAndHideFast(this._queuedToShow, this._queuedToHide); - this._queuedToShow = []; - this._queuedToHide = []; - } - - _ElementUtilities.removeClass(this._element, _Constants.hidingClass); - _ElementUtilities.addClass(this._element, _Constants.hiddenClass); - - // Send our "afterclose" event - this._sendEvent(EVENTS.afterClose); - this._writeProfilerMark("hide,StopTM"); - }, - - _animatePositionChange: function _LegacyAppBar_animatePositionChange(fromPosition, toPosition) { - // Determines and executes the proper transition between visible positions - - var layoutElementsAnimationPromise = this._layoutImpl.positionChanging(fromPosition, toPosition), - appBarElementAnimationPromise; - - // Get values in terms of pixels to perform animation. - var beginningVisiblePixelHeight = this._visiblePixels[fromPosition], - endingVisiblePixelHeight = this._visiblePixels[toPosition], - distance = Math.abs(endingVisiblePixelHeight - beginningVisiblePixelHeight), - offsetTop = (this._placement === _Constants.appBarPlacementTop) ? -distance : distance; - - if ((this._placement === _Constants.appBarPlacementTop) && - ((fromPosition === displayModeVisiblePositions.shown && - toPosition === displayModeVisiblePositions.compact) || - (fromPosition === displayModeVisiblePositions.compact && - toPosition === displayModeVisiblePositions.shown))) { - // Command icons remain in the same location on a top appbar - // when going from compact > shown or shown > compact. - offsetTop = 0; - } - - // Animate - if (endingVisiblePixelHeight > beginningVisiblePixelHeight) { - var fromOffset = { top: offsetTop + "px", left: "0px" }; - appBarElementAnimationPromise = Animations.showEdgeUI(this._element, fromOffset, { mechanism: "transition" }); - } else { - var toOffset = { top: offsetTop + "px", left: "0px" }; - appBarElementAnimationPromise = Animations.hideEdgeUI(this._element, toOffset, { mechanism: "transition" }); - } - - return Promise.join([layoutElementsAnimationPromise, appBarElementAnimationPromise]); - }, - - _checkDoNext: function _LegacyAppBar_checkDoNext() { - // Do nothing if we're still animating - if (this._animating || this._needToHandleShowingKeyboard || this._needToHandleHidingKeyboard || this._disposed) { - return; - } - - if (this._doNext === displayModeVisiblePositions.disabled || - this._doNext === displayModeVisiblePositions.hidden || - this._doNext === displayModeVisiblePositions.minimal || - this._doNext === displayModeVisiblePositions.compact) { - // Do hide first because animating commands would be easier - this._hide(this._doNext); - this._doNext = ""; - } else if (this._queuedCommandAnimation) { - // Do queued commands before showing if possible - this._showAndHideQueue(); - } else if (this._doNext === displayModeVisiblePositions.shown) { - // Show last so that we don't unnecessarily animate commands - this._show(); - this._doNext = ""; - } - }, - - // Set focus to the passed in _LegacyAppBar - _setFocusToAppBar: function _LegacyAppBar_setFocusToAppBar(useSetActive, scroller) { - if (!this._focusOnFirstFocusableElement(useSetActive, scroller)) { - // No first element, set it to appbar itself - _Overlay._Overlay._trySetActive(this._element, scroller); - } - }, - - _commandsUpdated: function _LegacyAppBar_commandsUpdated() { - // If we are still initializing then we don't have a layout yet so it doesn't need updating. - if (!this._initializing) { - this._layoutImpl.commandsUpdated(); - this._layoutImpl.scale(); - } - }, - - _beginAnimateCommands: function _LegacyAppBar_beginAnimateCommands(showCommands, hideCommands, otherVisibleCommands) { - // The parameters are 3 mutually exclusive arrays of win-command elements contained in this Overlay. - // 1) showCommands[]: All of the HIDDEN win-command elements that ARE scheduled to show. - // 2) hideCommands[]: All of the VISIBLE win-command elements that ARE scheduled to hide. - // 3) otherVisibleCommands[]: All VISIBLE win-command elements that ARE NOT scheduled to hide. - this._layoutImpl.beginAnimateCommands(showCommands, hideCommands, otherVisibleCommands); - }, - - _endAnimateCommands: function _LegacyAppBar_endAnimateCommands() { - this._layoutImpl.endAnimateCommands(); - this._endAnimateCommandsCallBack(); - }, - - _endAnimateCommandsCallBack: function _LegacyAppBar_endAnimateCommandsCallBack() { - // Leave this blank for unit tests to overwrite. - }, - - // Get the top offset for top appbars. - _getTopOfVisualViewport: function _LegacyAppBar_getTopOfVisualViewPort() { - return _Overlay._Overlay._keyboardInfo._visibleDocTop; - }, - - // Get the bottom offset for bottom appbars. - _getAdjustedBottom: function _LegacyAppBar_getAdjustedBottom() { - // Need the distance the IHM moved as well. - return _Overlay._Overlay._keyboardInfo._visibleDocBottomOffset; - }, - - _showingKeyboard: function _LegacyAppBar_showingKeyboard(event) { - // Remember keyboard showing state. - this._keyboardObscured = false; - this._needToHandleHidingKeyboard = false; - - // If we're already moved, then ignore the whole thing - if (_Overlay._Overlay._keyboardInfo._visible && this._alreadyInPlace()) { - return; - } - - this._needToHandleShowingKeyboard = true; - // If focus is in the appbar, don't cause scrolling. - if (this.opened && this._element.contains(_Global.document.activeElement)) { - event.ensuredFocusedElementInView = true; - } - - // Check if appbar moves or if we're ok leaving it obscured instead. - if (this._visible && this._placement !== _Constants.appBarPlacementTop && _Overlay._Overlay._isFlyoutVisible()) { - // Remember that we're obscured - this._keyboardObscured = true; - } else { - // Don't be obscured, clear _scrollHappened flag to give us inference later on when to re-show ourselves. - this._scrollHappened = false; - } - - // Also set timeout regardless, so we can clean up our _keyboardShowing flag. - var that = this; - _Global.setTimeout(function (e) { that._checkKeyboardTimer(e); }, _Overlay._Overlay._keyboardInfo._animationShowLength + _Overlay._Overlay._scrollTimeout); - }, - - _hidingKeyboard: function _LegacyAppBar_hidingKeyboard() { - // We'll either just reveal the current space under the IHM or restore the window height. - - // We won't be obscured - this._keyboardObscured = false; - this._needToHandleShowingKeyboard = false; - this._needToHandleHidingKeyboard = true; - - // We'll either just reveal the current space or resize the window - if (!_Overlay._Overlay._keyboardInfo._isResized) { - // If we're not completely hidden, only fake hiding under keyboard, or already animating, - // then snap us to our final position. - if (this._visible || this._animating) { - // Not resized, update our final position immediately - this._checkScrollPosition(); - this._element.style.display = ""; - } - this._needToHandleHidingKeyboard = false; - } - // Else resize should clear keyboardHiding. - }, - - _resize: function _LegacyAppBar_resize(event) { - // If we're hidden by the keyboard, then hide bottom appbar so it doesn't pop up twice when it scrolls - if (this._needToHandleShowingKeyboard) { - // Top is allowed to scroll off the top, but we don't want bottom to peek up when - // scrolled into view since we'll show it ourselves and don't want a stutter effect. - if (this._visible) { - if (this._placement !== _Constants.appBarPlacementTop && !this._keyboardObscured) { - // If viewport doesn't match window, need to vanish momentarily so it doesn't scroll into view, - // however we don't want to toggle the visibility="hidden" hidden flag. - this._element.style.display = "none"; - } - } - // else if we're top we stay, and if there's a flyout, stay obscured by the keyboard. - } else if (this._needToHandleHidingKeyboard) { - this._needToHandleHidingKeyboard = false; - if (this._visible || this._animating) { - // Snap to final position - this._checkScrollPosition(); - this._element.style.display = ""; - } - } - - // Make sure everything still fits. - if (!this._initializing) { - this._layoutImpl.resize(event); - } - }, - - _checkKeyboardTimer: function _LegacyAppBar_checkKeyboardTimer() { - if (!this._scrollHappened) { - this._mayEdgeBackIn(); - } - }, - - _manipulationChanged: function _LegacyAppBar_manipulationChanged(event) { - // See if we're at the not manipulating state, and we had a scroll happen, - // which is implicitly after the keyboard animated. - if (event.currentState === 0 && this._scrollHappened) { - this._mayEdgeBackIn(); - } - }, - - _mayEdgeBackIn: function _LegacyAppBar_mayEdgeBackIn() { - // May need to react to IHM being resized event - if (this._needToHandleShowingKeyboard) { - // If not top appbar or viewport isn't still at top, then need to show again - this._needToHandleShowingKeyboard = false; - // If obscured (IHM + flyout showing), it's ok to stay obscured. - // If bottom we have to move, or if top scrolled off screen. - if (!this._keyboardObscured && - (this._placement !== _Constants.appBarPlacementTop || _Overlay._Overlay._keyboardInfo._visibleDocTop !== 0)) { - var toPosition = this._visiblePosition; - this._lastPositionVisited = displayModeVisiblePositions.hidden; - this._changeVisiblePosition(toPosition, false); - } else { - // Ensure any animations dropped during the showing keyboard are caught up. - this._checkDoNext(); - } - } - this._scrollHappened = false; - }, - - _ensurePosition: function _LegacyAppBar_ensurePosition() { - // Position the _LegacyAppBar element relative to the top or bottom edge of the visible - // document, based on the the visible position we think we need to be in. - var offSet = this._computePositionOffset(); - this._element.style.bottom = offSet.bottom; - this._element.style.top = offSet.top; - - }, - - _computePositionOffset: function _LegacyAppBar_computePositionOffset() { - // Calculates and returns top and bottom offsets for the _LegacyAppBar element, relative to the top or bottom edge of the visible - // document. - var positionOffSet = {}; - - if (this._placement === _Constants.appBarPlacementBottom) { - // If the IHM is open, the bottom of the visual viewport may or may not be obscured - // Use _getAdjustedBottom to account for the IHM if it is covering the bottom edge. - positionOffSet.bottom = this._getAdjustedBottom() + "px"; - positionOffSet.top = ""; - } else if (this._placement === _Constants.appBarPlacementTop) { - positionOffSet.bottom = ""; - positionOffSet.top = this._getTopOfVisualViewport() + "px"; - } - - return positionOffSet; - }, - - _checkScrollPosition: function _LegacyAppBar_checkScrollPosition() { - // If IHM has appeared, then remember we may come in - if (this._needToHandleShowingKeyboard) { - // Tag that it's OK to edge back in. - this._scrollHappened = true; - return; - } - - // We only need to update if we're not completely hidden. - if (this._visible || this._animating) { - this._ensurePosition(); - // Ensure any animations dropped during the showing keyboard are caught up. - this._checkDoNext(); - } - }, - - _alreadyInPlace: function _LegacyAppBar_alreadyInPlace() { - // See if we're already where we're supposed to be. - var offSet = this._computePositionOffset(); - return (offSet.top === this._element.style.top && offSet.bottom === this._element.style.bottom); - }, - - // If there is a shown non-sticky _LegacyAppBar then it sets the firstDiv tabIndex to - // the minimum tabIndex found in the _LegacyAppBars and finalDiv to the max found. - // Otherwise sets their tabIndex to -1 so they are not tab stops. - _updateFirstAndFinalDiv: function _LegacyAppBar_updateFirstAndFinalDiv() { - var appBarFirstDiv = this._element.querySelectorAll("." + _Constants.firstDivClass); - appBarFirstDiv = appBarFirstDiv.length >= 1 ? appBarFirstDiv[0] : null; - - var appBarFinalDiv = this._element.querySelectorAll("." + _Constants.finalDivClass); - appBarFinalDiv = appBarFinalDiv.length >= 1 ? appBarFinalDiv[0] : null; - - // Remove the firstDiv & finalDiv if they are not at the appropriate locations - if (appBarFirstDiv && (this._element.children[0] !== appBarFirstDiv)) { - appBarFirstDiv.parentNode.removeChild(appBarFirstDiv); - appBarFirstDiv = null; - } - if (appBarFinalDiv && (this._element.children[this._element.children.length - 1] !== appBarFinalDiv)) { - appBarFinalDiv.parentNode.removeChild(appBarFinalDiv); - appBarFinalDiv = null; - } - - // Create and add the firstDiv & finalDiv if they don't already exist - if (!appBarFirstDiv) { - // Add a firstDiv that will be the first child of the appBar. - // On focus set focus to the last element of the AppBar. - appBarFirstDiv = _Global.document.createElement("div"); - // display: inline is needed so that the div doesn't take up space and cause the page to scroll on focus - appBarFirstDiv.style.display = "inline"; - appBarFirstDiv.className = _Constants.firstDivClass; - appBarFirstDiv.tabIndex = -1; - appBarFirstDiv.setAttribute("aria-hidden", "true"); - _ElementUtilities._addEventListener(appBarFirstDiv, "focusin", this._focusOnLastFocusableElementOrThis.bind(this), false); - // add to beginning - if (this._element.children[0]) { - this._element.insertBefore(appBarFirstDiv, this._element.children[0]); - } else { - this._element.appendChild(appBarFirstDiv); - } - } - if (!appBarFinalDiv) { - // Add a finalDiv that will be the last child of the appBar. - // On focus set focus to the first element of the AppBar. - appBarFinalDiv = _Global.document.createElement("div"); - // display: inline is needed so that the div doesn't take up space and cause the page to scroll on focus - appBarFinalDiv.style.display = "inline"; - appBarFinalDiv.className = _Constants.finalDivClass; - appBarFinalDiv.tabIndex = -1; - appBarFinalDiv.setAttribute("aria-hidden", "true"); - _ElementUtilities._addEventListener(appBarFinalDiv, "focusin", this._focusOnFirstFocusableElementOrThis.bind(this), false); - this._element.appendChild(appBarFinalDiv); - } - - - // invokeButton should be the second to last element in the _LegacyAppBar's tab order. Second to the finalDiv. - if (this._element.children[this._element.children.length - 2] !== this._invokeButton) { - this._element.insertBefore(this._invokeButton, appBarFinalDiv); - } - var elms = this._element.getElementsByTagName("*"); - var highestTabIndex = _ElementUtilities._getHighestTabIndexInList(elms); - this._invokeButton.tabIndex = highestTabIndex; - - // Update the tabIndex of the firstDiv & finalDiv - if (appBarFirstDiv) { - appBarFirstDiv.tabIndex = _ElementUtilities._getLowestTabIndexInList(elms); - } - if (appBarFinalDiv) { - appBarFinalDiv.tabIndex = highestTabIndex; - } - }, - - _writeProfilerMark: function _LegacyAppBar_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI._LegacyAppBar:" + this._id + ":" + text); - } - }, { - // Statics - _Events: EVENTS, - }); - - return _LegacyAppBar; - }) - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -// Menu -/// Menu,Menus,Flyout,Flyouts,Statics -define('WinJS/Controls/Menu',[ - 'exports', - '../Core/_Global', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_ErrorFromName', - '../Core/_Resources', - '../Core/_WriteProfilerMark', - '../Promise', - '../Utilities/_ElementUtilities', - '../Utilities/_Hoverable', - '../Utilities/_KeyboardBehavior', - './_LegacyAppBar/_Constants', - './Flyout', - './Flyout/_Overlay', - './Menu/_Command' -], function menuInit(exports, _Global, _Base, _BaseUtils, _ErrorFromName, _Resources, _WriteProfilerMark, Promise, _ElementUtilities, _Hoverable, _KeyboardBehavior, _Constants, Flyout, _Overlay, _Command) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// Represents a menu flyout for displaying commands. - /// - /// - /// Menu - /// - /// - /// - /// - /// ]]> - /// Raised just before showing a menu. - /// Raised immediately after a menu is fully shown. - /// Raised just before hiding a menu. - /// Raised immediately after a menu is fully hidden. - /// The Menu control itself - /// - /// - Menu: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/menuAriaLabel").value; }, - get requiresCommands() { return "Invalid argument: commands must not be empty"; }, - get nullCommand() { return "Invalid argument: command must not be null"; }, - }; - - function isCommandInMenu(object) { - // Verifies that we have a menuCommand element and that it is in a Menu. - var element = object.element || object; - return _ElementUtilities._matchesSelector(element, "." + _Constants.menuClass + " " + "." + _Constants.menuCommandClass); - } - - var Menu = _Base.Class.derive(Flyout.Flyout, function Menu_ctor(element, options) { - /// - /// - /// Creates a new Menu control. - /// - /// - /// The DOM element that will host the control. - /// - /// - /// The set of properties and values to apply to the control. - /// - /// The new Menu control. - /// - /// - - // We need to be built on top of a Flyout, so stomp on the user's input - options = options || {}; - - // Make sure there's an input element - this._element = element || _Global.document.createElement("div"); - this._id = this._element.id || _ElementUtilities._uniqueID(this._element); - this._writeProfilerMark("constructor,StartTM"); - - // validate that if they didn't set commands, in which - // case any HTML only contains commands. Do this first - // so that we don't leave partial Menus in the DOM. - if (!options.commands && this._element) { - // Shallow copy object so we can modify it. - options = _BaseUtils._shallowCopy(options); - options.commands = this._verifyCommandsOnly(this._element, "WinJS.UI.MenuCommand"); - } - - // Remember aria role in case base constructor changes it - var role = this._element ? this._element.getAttribute("role") : null; - var label = this._element ? this._element.getAttribute("aria-label") : null; - - // Call the base overlay constructor helper - this._baseFlyoutConstructor(this._element, options); - - // Make sure we have an ARIA role - if (role === null || role === "" || role === undefined) { - this._element.setAttribute("role", "menu"); - } - if (label === null || label === "" || label === undefined) { - this._element.setAttribute("aria-label", strings.ariaLabel); - } - - // Handle "esc" & "up/down" key presses - this._element.addEventListener("keydown", this._handleKeyDown.bind(this), true); - this._element.addEventListener(_Constants._menuCommandInvokedEvent, this._handleCommandInvoked.bind(this), false); - this._element.addEventListener("mouseover", this._handleMouseOver.bind(this), false); - this._element.addEventListener("mouseout", this._handleMouseOut.bind(this), false); - - // Attach our css class - _ElementUtilities.addClass(this._element, _Constants.menuClass); - - this._winKeyboard = new _KeyboardBehavior._WinKeyboard(this._element); - - // Need to set our commands, making sure we're hidden first - this.hide(); - this._writeProfilerMark("constructor,StopTM"); - }, { - // Public Properties - - /// - /// Sets the MenuCommand objects that appear in the Menu. You can set this to a single MenuCommand or an array of MenuCommand objects. - /// - /// - commands: { - set: function (value) { - // Fail if trying to set when visible - if (!this.hidden) { - throw new _ErrorFromName("WinJS.UI.Menu.CannotChangeCommandsWhenVisible", _Resources._formatString(_Overlay._Overlay.commonstrings.cannotChangeCommandsWhenVisible, "Menu")); - } - - // Start from scratch - _ElementUtilities.empty(this._element); - - // In case they had only one... - if (!Array.isArray(value)) { - value = [value]; - } - - // Add commands - var len = value.length; - for (var i = 0; i < len; i++) { - this._addCommand(value[i]); - } - } - }, - - getCommandById: function (id) { - /// - /// - /// Retrieve the command with the specified ID from this Menu. If more than one command is found, all are returned. - /// - /// The ID of the command to find. - /// - /// The command found, an array of commands if more than one have the same ID, or null if no command is found. - /// - /// - /// - var commands = this.element.querySelectorAll("#" + id); - var newCommands = []; - for (var count = 0, len = commands.length; count < len; count++) { - if (commands[count].winControl) { - newCommands.push(commands[count].winControl); - } - } - - if (newCommands.length === 1) { - return newCommands[0]; - } else if (newCommands.length === 0) { - return null; - } - - return newCommands; - }, - - - showCommands: function (commands) { - /// - /// - /// Shows the specified commands of the Menu. - /// - /// - /// The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. - /// - /// - /// - if (!commands) { - throw new _ErrorFromName("WinJS.UI.Menu.RequiresCommands", strings.requiresCommands); - } - - this._showCommands(commands, true); - }, - - hideCommands: function (commands) { - /// - /// - /// Hides the Menu. - /// - /// - /// Required. Command or Commands to hide, either String, DOM elements, or WinJS objects. - /// - /// - /// - if (!commands) { - throw new _ErrorFromName("WinJS.UI.Menu.RequiresCommands", strings.requiresCommands); - } - - this._hideCommands(commands, true); - }, - - showOnlyCommands: function (commands) { - /// - /// - /// Shows the specified commands of the Menu while hiding all other commands. - /// - /// - /// The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. - /// - /// - /// - if (!commands) { - throw new _ErrorFromName("WinJS.UI.Menu.RequiresCommands", strings.requiresCommands); - } - - this._showOnlyCommands(commands, true); - }, - - show: function (anchor, placement, alignment) { - /// - /// - /// Shows the Menu, if hidden, regardless of other states. - /// - /// - /// The DOM element, or ID of a DOM element, to anchor the Menu. This parameter overrides the anchor property for this method call only. - /// - /// - /// The placement of the Menu to the anchor: 'auto' (default), 'autohorizontal', 'autovertical', 'top', 'bottom', 'left', or 'right'. This parameter overrides the placement - /// property for this method call only. - /// - /// - /// For 'top' or 'bottom' placement, the alignment of the Menu to the anchor's edge: 'center' (default), 'left', or 'right'. This parameter - /// overrides the alignment property for this method call only. - /// - /// - /// - // Just call private version to make appbar flags happy - this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). - this._show(anchor, placement, alignment); - }, - - _show: function Menu_show(anchor, placement, alignment) { - if (!_ElementUtilities.hasClass(this.element, _Constants.menuMouseSpacingClass) && !_ElementUtilities.hasClass(this.element, _Constants.menuTouchSpacingClass)) { - // The Menu's spacing shouldn't change while it is already shown. Only - // add a spacing class if it doesn't already have one. It will get - // removed after the Menu hides. - _ElementUtilities.addClass( - this.element, - Flyout.Flyout._cascadeManager.inputType === _KeyboardBehavior._InputTypes.mouse || Flyout.Flyout._cascadeManager.inputType === _KeyboardBehavior._InputTypes.keyboard ? - _Constants.menuMouseSpacingClass : - _Constants.menuTouchSpacingClass - ); - } - // Call flyout show - this._baseFlyoutShow(anchor, placement, alignment); - - // Menu will need to adjust MenuCommand layouts based on the various - // types of commands visible in our Menu, but only after we send the beforeshow - // event, so the developer has a chance to show or hide more commands. - // Flyout's _findPosition will make that call. - }, - - _hide: function Menu_hide() { - if (this._hoverPromise) { - this._hoverPromise.cancel(); - } - Flyout.Flyout.prototype._hide.call(this); - }, - - _beforeEndHide: function Menu_beforeEndHide() { - _ElementUtilities.removeClass(this.element, _Constants.menuMouseSpacingClass); - _ElementUtilities.removeClass(this.element, _Constants.menuTouchSpacingClass); - Flyout.Flyout.prototype._beforeEndHide.call(this); - }, - - _addCommand: function Menu_addCommand(command) { - if (!command) { - throw new _ErrorFromName("WinJS.UI.Menu.NullCommand", strings.nullCommand); - } - // See if it's a command already - if (!command._element) { - // Not a command, so assume it's options for a command - command = new _Command.MenuCommand(null, command); - } - // If we were attached somewhere else, detach us - if (command._element.parentElement) { - command._element.parentElement.removeChild(command._element); - } - - // Reattach us - this._element.appendChild(command._element); - }, - - _dispose: function Menu_dispose() { - if (this._hoverPromise) { - this._hoverPromise.cancel(); - } - Flyout.Flyout.prototype._dispose.call(this); - - }, - - _commandsUpdated: function Menu_commandsUpdated() { - if (!this.hidden) { - this._checkMenuCommands(); - } - }, - - // Called when we show/hide commands or by flyout's _findPosition when the Menu is showing. - _checkMenuCommands: function Menu_checkMenuCommands() { - var menuCommands = this._element.querySelectorAll(".win-command"), - hasToggleCommands = false, - hasFlyoutCommands = false; - if (menuCommands) { - for (var i = 0, len = menuCommands.length; i < len; i++) { - var menuCommand = menuCommands[i].winControl; - if (menuCommand && !menuCommand.hidden) { - if (!hasToggleCommands && menuCommand.type === _Constants.typeToggle) { - hasToggleCommands = true; - } - if (!hasFlyoutCommands && menuCommand.type === _Constants.typeFlyout) { - hasFlyoutCommands = true; - } - } - } - } - - _ElementUtilities[hasToggleCommands ? 'addClass' : 'removeClass'](this._element, _Constants.menuContainsToggleCommandClass); - _ElementUtilities[hasFlyoutCommands ? 'addClass' : 'removeClass'](this._element, _Constants.menuContainsFlyoutCommandClass); - }, - - _handleKeyDown: function Menu_handleKeyDown(event) { - if (event.keyCode === Key.upArrow) { - Menu._focusOnPreviousElement(this.element); - - // Prevent the page from scrolling - event.preventDefault(); - } else if (event.keyCode === Key.downArrow) { - Menu._focusOnNextElement(this.element); - - // Prevent the page from scrolling - event.preventDefault(); - } else if ((event.keyCode === Key.space || event.keyCode === Key.enter) - && (this.element === _Global.document.activeElement)) { - event.preventDefault(); - this.hide(); - } else if (event.keyCode === Key.tab) { - event.preventDefault(); - } - }, - - _handleFocusIn: function Menu_handleFocusIn(event) { - // Menu focuses commands on mouseover. We need to handle cases involving activated flyout commands - // to ensure that mousing over different commands in a menu closes that command's sub flyout. - var target = event.target; - if (isCommandInMenu(target)) { - var command = target.winControl; - if (_ElementUtilities.hasClass(command.element, _Constants.menuCommandFlyoutActivatedClass)) { - // If it's an activated 'flyout' typed command, move focus onto the command's subFlyout. - // We expect this will collapse all decendant Flyouts of the subFlyout from the cascade. - command.flyout.element.focus(); - } else { - // Deactivate any currently activated command in the Menu to subsequently trigger all subFlyouts descendants to collapse. - var activatedSiblingCommand = this.element.querySelector("." + _Constants.menuCommandFlyoutActivatedClass); - if (activatedSiblingCommand) { - _Command.MenuCommand._deactivateFlyoutCommand(activatedSiblingCommand); - } - } - } else if (target === this.element) { - // The Menu itself is receiving focus. Rely on the Flyout base implementation to notify the cascadeManager. - // We expect this will only happen when other Menu event handling code causes the Menu to focus itself. - Flyout.Flyout.prototype._handleFocusIn.call(this, event); - } - }, - - _handleCommandInvoked: function Menu_handleCommandInvoked(event) { - // Cascading Menus hide when invoking a command commits an action, not when invoking a command opens a subFlyout. - if (this._hoverPromise) { - // Prevent pending duplicate invoke triggered via hover. - this._hoverPromise.cancel(); - } - var command = event.detail.command; - if (command._type !== _Constants.typeFlyout && command._type !== _Constants.typeSeparator) { - this._lightDismiss(); // Collapse all Menus/Flyouts. - } - }, - - _hoverPromise: null, - _handleMouseOver: function Menu_handleMouseOver(event) { - var target = event.target; - if (isCommandInMenu(target)) { - var command = target.winControl, - that = this; - - if (target.focus) { - target.focus(); - // remove keyboard focus rect since focus has been triggered by mouse over. - _ElementUtilities.removeClass(target, "win-keyboard"); - - if (command.type === _Constants.typeFlyout && command.flyout && command.flyout.hidden) { - this._hoverPromise = this._hoverPromise || Promise.timeout(_Constants.menuCommandHoverDelay).then( - function () { - if (!that.hidden && !that._disposed) { - command._invoke(event); - } - that._hoverPromise = null; - }, - function () { - that._hoverPromise = null; - }); - } - } - } - }, - - _handleMouseOut: function Menu_handleMouseOut(event) { - var target = event.target; - if (isCommandInMenu(target) && !target.contains(event.relatedTarget)) { - if (target === _Global.document.activeElement) { - // Menu gives focus to the menu itself - this.element.focus(); - } - if (this._hoverPromise) { - this._hoverPromise.cancel(); - } - } - }, - - _writeProfilerMark: function Menu_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI.Menu:" + this._id + ":" + text); - } - }); - - // Statics - - // Set focus to next focusable element in the menu (loop if necessary). - // Note: The loop works by first setting focus to the menu itself. If the menu is - // what had focus before, then we break. Otherwise we try the first child next. - // Focus remains on the menu if nothing is focusable. - Menu._focusOnNextElement = function (menu) { - var _currentElement = _Global.document.activeElement; - - do { - if (_currentElement === menu) { - _currentElement = _currentElement.firstElementChild; - } else { - _currentElement = _currentElement.nextElementSibling; - } - - if (_currentElement) { - _currentElement.focus(); - } else { - _currentElement = menu; - } - - } while (_currentElement !== _Global.document.activeElement); - }; - - // Set focus to previous focusable element in the menu (loop if necessary). - // Note: The loop works by first setting focus to the menu itself. If the menu is - // what had focus before, then we break. Otherwise we try the last child next. - // Focus remains on the menu if nothing is focusable. - Menu._focusOnPreviousElement = function (menu) { - var _currentElement = _Global.document.activeElement; - - do { - if (_currentElement === menu) { - _currentElement = _currentElement.lastElementChild; - } else { - _currentElement = _currentElement.previousElementSibling; - } - - if (_currentElement) { - _currentElement.focus(); - } else { - _currentElement = menu; - } - - } while (_currentElement !== _Global.document.activeElement); - }; - - return Menu; - }) - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/AutoSuggestBox/_SearchSuggestionManagerShim',[ - 'exports', - '../../_Signal', - '../../Core/_Base', - '../../Core/_BaseUtils', - '../../Core/_Events', - '../../BindingList', -], function SearchSuggestionManagerShimInit(exports, _Signal, _Base, _BaseUtils, _Events, BindingList) { - "use strict"; - - var CollectionChange = { - reset: 0, - itemInserted: 1, - itemRemoved: 2, - itemChanged: 3 - }; - var SearchSuggestionKind = { - Query: 0, - Result: 1, - Separator: 2 - }; - - var SuggestionVectorShim = _Base.Class.derive(Array, function SuggestionVectorShim_ctor() { - }, { - reset: function () { - this.length = 0; - this.dispatchEvent("vectorchanged", { collectionChange: CollectionChange.reset, index: 0 }); - }, - - insert: function (index, data) { - this.splice(index, 0, data); - this.dispatchEvent("vectorchanged", { collectionChange: CollectionChange.itemInserted, index: index }); - }, - - remove: function (index) { - this.splice(index, 1); - this.dispatchEvent("vectorchanged", { collectionChange: CollectionChange.itemRemoved, index: index }); - }, - }); - _Base.Class.mix(SuggestionVectorShim, _Events.eventMixin); - - var SearchSuggestionCollectionShim = _Base.Class.define(function SearchSuggestionCollectionShim_ctor() { - this._data = []; - }, { - size: { - get: function () { - return this._data.length; - } - }, - - appendQuerySuggestion: function (text) { - this._data.push({ kind: SearchSuggestionKind.Query, text: text }); - }, - appendQuerySuggestions: function (suggestions) { - suggestions.forEach(this.appendQuerySuggestion.bind(this)); - }, - appendResultSuggestion: function (text, detailText, tag, imageUrl, imageAlternateText) { - // 'image' must be null (not undefined) for SearchBox to fallback to use imageUrl instead - this._data.push({ kind: SearchSuggestionKind.Result, text: text, detailText: detailText, tag: tag, imageUrl: imageUrl, imageAlternateText: imageAlternateText, image: null }); - }, - appendSearchSeparator: function (label) { - this._data.push({ kind: SearchSuggestionKind.Separator, text: label }); - } - }); - - var SuggestionsRequestedEventArgShim = _Base.Class.define(function SuggestionsRequestedEventArgShim_ctor(queryText, language, linguisticDetails) { - this._queryText = queryText; - this._language = language; - this._linguisticDetails = linguisticDetails; - this._searchSuggestionCollection = new SearchSuggestionCollectionShim(); - }, { - language: { - get: function () { - return this._language; - } - }, - linguisticDetails: { - get: function () { - return this._linguisticDetails; - } - }, - queryText: { - get: function () { - return this._queryText; - } - }, - searchSuggestionCollection: { - get: function () { - return this._searchSuggestionCollection; - } - }, - getDeferral: function () { - return this._deferralSignal || (this._deferralSignal = new _Signal()); - }, - - _deferralSignal: null, - }); - - var SearchSuggestionManagerShim = _Base.Class.define(function SearchSuggestionManagerShim_ctor() { - this._updateVector = this._updateVector.bind(this); - - this._suggestionVector = new SuggestionVectorShim(); - this._query = ""; - this._history = { "": [] }; - - this._dataSource = []; - - this.searchHistoryContext = ""; - this.searchHistoryEnabled = true; - }, { - addToHistory: function (queryText /*, language */) { - if (!queryText || !queryText.trim()) { - return; - } - - var history = this._history[this.searchHistoryContext]; - var dupeIndex = -1; - for (var i = 0, l = history.length; i < l; i++) { - var item = history[i]; - if (item.text.toLowerCase() === queryText.toLowerCase()) { - dupeIndex = i; - break; - } - } - if (dupeIndex >= 0) { - history.splice(dupeIndex, 1); - } - - history.splice(0, 0, { text: queryText, kind: SearchSuggestionKind.Query }); - this._updateVector(); - }, - - clearHistory: function () { - this._history[this.searchHistoryContext] = []; - this._updateVector(); - }, - - setLocalContentSuggestionSettings: function (settings) { - }, - - setQuery: function (queryText) { - var that = this; - function update(arr) { - that._dataSource = arr; - that._updateVector(); - } - - this._query = queryText; - var arg = new SuggestionsRequestedEventArgShim(queryText); - this.dispatchEvent("suggestionsrequested", { request: arg }); - if (arg._deferralSignal) { - arg._deferralSignal.promise.then(update.bind(this, arg.searchSuggestionCollection._data)); - } else { - update(arg.searchSuggestionCollection._data); - } - }, - - searchHistoryContext: { - get: function () { - return "" + this._searchHistoryContext; - }, - set: function (value) { - value = "" + value; - if (!this._history[value]) { - this._history[value] = []; - } - this._searchHistoryContext = value; - } - }, - - searchHistoryEnabled: { - get: function () { - return this._searchHistoryEnabled; - }, - set: function (value) { - this._searchHistoryEnabled = value; - } - }, - - suggestions: { - get: function () { - return this._suggestionVector; - } - }, - - _updateVector: function () { - // Can never clear the entire suggestions list or it will cause a visual flash because - // the SearchBox control removes the suggestions list UI when the SSM fires vectorChanged - // with size === 0, then re-renders it when the first suggestion is added. - // Workaround is to insert a dummy entry, remove all old entries, add the new set of - // eligible suggestions, then remove the dummy entry. - this.suggestions.insert(this.suggestions.length, { text: "", kind: SearchSuggestionKind.Query }); - - while (this.suggestions.length > 1) { - this.suggestions.remove(0); - } - - var index = 0; - var added = {}; - if (this.searchHistoryEnabled) { - var q = this._query.toLowerCase(); - this._history[this.searchHistoryContext].forEach(function (item) { - var text = item.text.toLowerCase(); - if (text.indexOf(q) === 0) { - this.suggestions.insert(index, item); - added[text] = true; - index++; - } - }, this); - } - this._dataSource.forEach(function (item) { - if (item.kind === SearchSuggestionKind.Query) { - if (!added[item.text.toLowerCase()]) { - this.suggestions.insert(index, item); - index++; - } - } else { - this.suggestions.insert(index, item); - index++; - } - }, this); - - this.suggestions.remove(this.suggestions.length - 1); - }, - }); - _Base.Class.mix(SearchSuggestionManagerShim, _Events.eventMixin); - - _Base.Namespace._moduleDefine(exports, null, { - _CollectionChange: CollectionChange, - _SearchSuggestionKind: SearchSuggestionKind, - _SearchSuggestionManagerShim: SearchSuggestionManagerShim, - }); -}); - -define('require-style!less/styles-autosuggestbox',[],function(){}); - -define('require-style!less/colors-autosuggestbox',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/AutoSuggestBox',[ - "exports", - "../Core/_Global", - "../Core/_WinRT", - "../Core/_Base", - "../Core/_ErrorFromName", - "../Core/_Events", - "../Core/_Resources", - "../Utilities/_Control", - "../Utilities/_ElementListUtilities", - "../Utilities/_ElementUtilities", - '../Utilities/_Hoverable', - "../_Accents", - "../Animations", - "../BindingList", - "../Promise", - "./Repeater", - "./AutoSuggestBox/_SearchSuggestionManagerShim", - "require-style!less/styles-autosuggestbox", - "require-style!less/colors-autosuggestbox" -], function autoSuggestBoxInit(exports, _Global, _WinRT, _Base, _ErrorFromName, _Events, _Resources, _Control, _ElementListUtilities, _ElementUtilities, _Hoverable, _Accents, Animations, BindingList, Promise, Repeater, _SuggestionManagerShim) { - "use strict"; - - _Accents.createAccentRule("html.win-hoverable .win-autosuggestbox .win-autosuggestbox-suggestion-selected:hover", [{ name: "background-color", value: _Accents.ColorTypes.listSelectHover }]); - _Accents.createAccentRule(".win-autosuggestbox .win-autosuggestbox-suggestion-selected", [{ name: "background-color", value: _Accents.ColorTypes.listSelectRest }]); - _Accents.createAccentRule(".win-autosuggestbox .win-autosuggestbox-suggestion-selected.win-autosuggestbox-suggestion-selected:hover:active", [{ name: "background-color", value: _Accents.ColorTypes.listSelectPress }]); - - var ClassNames = { - asb: "win-autosuggestbox", - asbDisabled: "win-autosuggestbox-disabled", - asbFlyout: "win-autosuggestbox-flyout", - asbFlyoutAbove: "win-autosuggestbox-flyout-above", - asbBoxFlyoutHighlightText: "win-autosuggestbox-flyout-highlighttext", - asbHitHighlightSpan: "win-autosuggestbox-hithighlight-span", - asbInput: "win-autosuggestbox-input", - asbInputFocus: "win-autosuggestbox-input-focus", - asbSuggestionQuery: "win-autosuggestbox-suggestion-query", - asbSuggestionResult: "win-autosuggestbox-suggestion-result", - asbSuggestionResultText: "win-autosuggestbox-suggestion-result-text", - asbSuggestionResultDetailedText: "win-autosuggestbox-suggestion-result-detailed-text", - asbSuggestionSelected: "win-autosuggestbox-suggestion-selected", - asbSuggestionSeparator: "win-autosuggestbox-suggestion-separator", - }; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// - /// A rich input box that provides suggestions as the user types. - /// - /// - /// - /// - /// - /// ]]> - /// Raised when user or app changes the query text. - /// Raised when user presses Enter. - /// Raised when user clicks one of the displayed suggestions. - /// Raised when the system requests suggestions from this app. - /// Styles the entire Auto Suggest Box control. - /// Styles the query input box. - /// Styles the result suggestions flyout. - /// Styles the query type suggestion. - /// Styles the result type suggestion. - /// Styles the currently selected suggestion. - /// Styles the separator type suggestion. - /// - /// - AutoSuggestBox: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - var EventNames = { - querychanged: "querychanged", - querysubmitted: "querysubmitted", - resultsuggestionchosen: "resultsuggestionchosen", - suggestionsrequested: "suggestionsrequested" - }; - - var Strings = { - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get invalidSuggestionKind() { return "Error: Invalid suggestion kind."; }, - - get ariaLabel() { return _Resources._getWinJSString("ui/autoSuggestBoxAriaLabel").value; }, - get ariaLabelInputNoPlaceHolder() { return _Resources._getWinJSString("ui/autoSuggestBoxAriaLabelInputNoPlaceHolder").value; }, - get ariaLabelInputPlaceHolder() { return _Resources._getWinJSString("ui/autoSuggestBoxAriaLabelInputPlaceHolder").value; }, - get ariaLabelQuery() { return _Resources._getWinJSString("ui/autoSuggestBoxAriaLabelQuery").value; }, - get ariaLabelResult() { return _Resources._getWinJSString("ui/autoSuggestBoxAriaLabelResult").value; }, - get ariaLabelSeparator() { return _Resources._getWinJSString("ui/autoSuggestBoxAriaLabelSeparator").value; }, - }; - - var AutoSuggestBox = _Base.Class.define(function asb_ctor(element, options) { - /// - /// - /// Creates a new AutoSuggestBox. - /// - /// - /// The DOM element that hosts the AutoSuggestBox. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". For example, to provide a handler for the querychanged event, - /// add a property named "onquerychanged" to the options object and set its value to the event handler. - /// This parameter is optional. - /// - /// - /// The new AutoSuggestBox. - /// - /// - /// - element = element || _Global.document.createElement("div"); - options = options || {}; - - if (element.winControl) { - throw new _ErrorFromName("WinJS.UI.AutoSuggestBox.DuplicateConstruction", Strings.duplicateConstruction); - } - - this._suggestionsChangedHandler = this._suggestionsChangedHandler.bind(this); - this._suggestionsRequestedHandler = this._suggestionsRequestedHandler.bind(this); - - this._element = element; - element.winControl = this; - element.classList.add(ClassNames.asb); - element.classList.add("win-disposable"); - - this._setupDOM(); - this._setupSSM(); - - this._chooseSuggestionOnEnter = false; - this._currentFocusedIndex = -1; - this._currentSelectedIndex = -1; - this._flyoutOpenPromise = Promise.wrap(); - this._lastKeyPressLanguage = ""; - this._prevLinguisticDetails = this._getLinguisticDetails(); - this._prevQueryText = ""; - - _Control.setOptions(this, options); - - this._hideFlyout(); - }, { - /// - /// Raised when user clicks on one of the suggestions displayed. - /// - /// - onresultsuggestionchosen: _Events._createEventProperty(EventNames.resultsuggestionchosen), - - /// - /// Raised when user or app changes the query text. - /// - /// - onquerychanged: _Events._createEventProperty(EventNames.querychanged), - - /// - /// Raised when user submits the current query. - /// - /// - onquerysubmitted: _Events._createEventProperty(EventNames.querysubmitted), - - /// - /// Raised when Windows requests search suggestions from the app. - /// - /// - onsuggestionsrequested: _Events._createEventProperty(EventNames.suggestionsrequested), - - /// - element: { - get: function () { - return this._element; - } - }, - - /// - /// Gets or sets whether the first suggestion is chosen when the user presses Enter. When set to true, as the user types in the input box, a - /// focus rectangle is drawn on the first suggestion (if present and no IME composition in progress). Pressing enter will behave the same as - /// if clicked on the focused suggestion, and the down arrow key press will put real focus to the second suggestion and the up arrow key will - /// remove focus. - /// - /// - chooseSuggestionOnEnter: { - get: function () { - return this._chooseSuggestionOnEnter; - }, - set: function (value) { - this._chooseSuggestionOnEnter = !!value; - } - }, - - /// - /// Gets or sets a value that specifies whether the AutoSuggestBox is disabled. - /// - /// - disabled: { - get: function () { - return this._inputElement.disabled; - }, - set: function (value) { - if (this._inputElement.disabled === !!value) { - return; - } - - if (!value) { - this._enableControl(); - } else { - this._disableControl(); - } - } - }, - - /// - /// Gets or sets the placeholder text for the AutoSuggestBox. This text is displayed if there is no other text in the input box. - /// - /// - placeholderText: { - get: function () { - return this._inputElement.placeholder; - }, - set: function (value) { - this._inputElement.placeholder = value; - this._updateInputElementAriaLabel(); - } - }, - - /// - /// Gets or sets the query text for the AutoSuggestBox. - /// - /// - queryText: { - get: function () { - return this._inputElement.value; - }, - set: function (value) { - this._inputElement.value = ""; // This finalizes the IME composition - this._inputElement.value = value; - } - }, - - /// - /// Gets or sets a value that specifies whether history is disabled for the AutoSuggestBox. The default value is false. - /// - /// - searchHistoryDisabled: { - get: function () { - return !this._suggestionManager.searchHistoryEnabled; - }, - set: function (value) { - this._suggestionManager.searchHistoryEnabled = !value; - } - }, - - /// - /// Gets or sets the search history context for the AutoSuggestBox. The search history context string is used as a secondary key for storing search history. - /// (The primary key is the AppId.) An app can use the search history context string to store different search histories based on the context of the application. - /// If you don't set this property, the system assumes that all searches in your app occur in the same context. - /// If you update this property while the search pane is open with suggestions showing, the changes won't take effect until the user enters the next character. - /// - /// - searchHistoryContext: { - get: function () { - return this._suggestionManager.searchHistoryContext; - }, - set: function (value) { - this._suggestionManager.searchHistoryContext = value; - } - }, - - dispose: function asb_dispose() { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - - // Cancel pending promises. - this._flyoutOpenPromise.cancel(); - - this._suggestions.removeEventListener("vectorchanged", this._suggestionsChangedHandler); - this._suggestionManager.removeEventListener("suggestionsrequested", this._suggestionsRequestedHandler); - - this._suggestionManager = null; - this._suggestions = null; - this._hitFinder = null; - - this._disposed = true; - }, - - setLocalContentSuggestionSettings: function asb_setLocalContentSuggestionSettings(settings) { - /// - /// - /// Specifies whether suggestions based on local files are automatically displayed in the input field, and defines the criteria that - /// the system uses to locate and filter these suggestions. - /// - /// - /// The new settings for local content suggestions. - /// - /// - /// - this._suggestionManager.setLocalContentSuggestionSettings(settings); - }, - - // Constructor Helpers - _setupDOM: function asb_setupDOM() { - var flyoutPointerReleasedHandler = this._flyoutPointerReleasedHandler.bind(this); - var inputOrImeChangeHandler = this._inputOrImeChangeHandler.bind(this); - - // Root element - if (!this._element.getAttribute("aria-label")) { - this._element.setAttribute("aria-label", Strings.ariaLabel); - } - this._element.setAttribute("role", "group"); - - // Input element - this._inputElement = _Global.document.createElement("input"); - this._inputElement.autocorrect = "off"; - this._inputElement.type = "search"; - this._inputElement.classList.add(ClassNames.asbInput); - this._inputElement.classList.add("win-textbox"); - this._inputElement.setAttribute("role", "textbox"); - this._inputElement.addEventListener("keydown", this._keyDownHandler.bind(this)); - this._inputElement.addEventListener("keypress", this._keyPressHandler.bind(this)); - this._inputElement.addEventListener("keyup", this._keyUpHandler.bind(this)); - this._inputElement.addEventListener("focus", this._inputFocusHandler.bind(this)); - this._inputElement.addEventListener("blur", this._inputBlurHandler.bind(this)); - this._inputElement.addEventListener("input", inputOrImeChangeHandler); - this._inputElement.addEventListener("compositionstart", inputOrImeChangeHandler); - this._inputElement.addEventListener("compositionupdate", inputOrImeChangeHandler); - this._inputElement.addEventListener("compositionend", inputOrImeChangeHandler); - _ElementUtilities._addEventListener(this._inputElement, "pointerdown", this._inputPointerDownHandler.bind(this)); - this._updateInputElementAriaLabel(); - this._element.appendChild(this._inputElement); - var context = this._tryGetInputContext(); - if (context) { - context.addEventListener("MSCandidateWindowShow", this._msCandidateWindowShowHandler.bind(this)); - context.addEventListener("MSCandidateWindowHide", this._msCandidateWindowHideHandler.bind(this)); - } - - // Flyout element - this._flyoutElement = _Global.document.createElement("div"); - this._flyoutElement.classList.add(ClassNames.asbFlyout); - this._flyoutElement.addEventListener("blur", this._flyoutBlurHandler.bind(this)); - _ElementUtilities._addEventListener(this._flyoutElement, "pointerup", flyoutPointerReleasedHandler); - _ElementUtilities._addEventListener(this._flyoutElement, "pointercancel", flyoutPointerReleasedHandler); - _ElementUtilities._addEventListener(this._flyoutElement, "pointerout", flyoutPointerReleasedHandler); - _ElementUtilities._addEventListener(this._flyoutElement, "pointerdown", this._flyoutPointerDownHandler.bind(this)); - this._element.appendChild(this._flyoutElement); - - // Repeater - var that = this; - function repeaterTemplate(suggestion) { - return that._renderSuggestion(suggestion); - } - this._suggestionsData = new BindingList.List(); - this._repeaterElement = _Global.document.createElement("div"); - this._repeater = new Repeater.Repeater(this._repeaterElement, { - data: this._suggestionsData, - template: repeaterTemplate, - }); - _ElementUtilities._ensureId(this._repeaterElement); - this._repeaterElement.setAttribute("role", "listbox"); - this._repeaterElement.setAttribute("aria-live", "polite"); - this._flyoutElement.appendChild(this._repeaterElement); - }, - - _setupSSM: function asb_setupSSM() { - // Get the search suggestion provider if it is available - this._suggestionManager = new _SuggestionManagerShim._SearchSuggestionManagerShim(); - this._suggestions = this._suggestionManager.suggestions; - - this._suggestions.addEventListener("vectorchanged", this._suggestionsChangedHandler); - this._suggestionManager.addEventListener("suggestionsrequested", this._suggestionsRequestedHandler); - }, - - // Flyout functions - _hideFlyout: function asb_hideFlyout() { - if (this._isFlyoutShown()) { - this._flyoutElement.style.display = "none"; - } - }, - - _showFlyout: function asb_showFlyout() { - var prevNumSuggestions = this._prevNumSuggestions || 0; - this._prevNumSuggestions = this._suggestionsData.length; - - if (this._isFlyoutShown() && prevNumSuggestions === this._suggestionsData.length) { - return; - } - - if (this._suggestionsData.length === 0) { - return; - } - - this._flyoutElement.style.display = "block"; - - var inputRect = this._inputElement.getBoundingClientRect(); - var flyoutRect = this._flyoutElement.getBoundingClientRect(); - var documentClientWidth = _Global.document.documentElement.clientWidth; - - // Display above vs below - the ASB flyout always opens in the direction where there is more space - var spaceAbove = inputRect.top; - var spaceBelow = _Global.document.documentElement.clientHeight - inputRect.bottom; - this._flyoutBelowInput = spaceBelow >= spaceAbove; - if (this._flyoutBelowInput) { - this._flyoutElement.classList.remove(ClassNames.asbFlyoutAbove); - this._flyoutElement.scrollTop = 0; - } else { - this._flyoutElement.classList.add(ClassNames.asbFlyoutAbove); - this._flyoutElement.scrollTop = this._flyoutElement.scrollHeight - this._flyoutElement.clientHeight; - } - - this._addFlyoutIMEPaddingIfRequired(); - - // Align left vs right edge - var alignRight; - if (_Global.getComputedStyle(this._flyoutElement).direction === "rtl") { - // RTL: Align to the right edge if there is enough space to the left of the control's - // right edge, or if there is not enough space to fit the flyout aligned to either edge. - alignRight = ((inputRect.right - flyoutRect.width) >= 0) || ((inputRect.left + flyoutRect.width) > documentClientWidth); - - } else { - // LTR: Align to the right edge if there isn't enough space to the right of the control's - // left edge, but there is enough space to the left of the control's right edge. - alignRight = ((inputRect.left + flyoutRect.width) > documentClientWidth) && ((inputRect.right - flyoutRect.width) >= 0); - } - - if (alignRight) { - this._flyoutElement.style.left = (inputRect.width - flyoutRect.width - this._element.clientLeft) + "px"; - } else { - this._flyoutElement.style.left = "-" + this._element.clientLeft + "px"; - } - - // ms-scroll-chaining:none will still chain scroll parent element if child div does - // not have a scroll bar. Prevent this by setting and updating touch action - this._flyoutElement.style.touchAction = this._flyoutElement.scrollHeight > flyoutRect.height ? "pan-y" : "none"; - - this._flyoutOpenPromise.cancel(); - var animationKeyframe = this._flyoutBelowInput ? "WinJS-flyoutBelowASB-showPopup" : "WinJS-flyoutAboveASB-showPopup"; - this._flyoutOpenPromise = Animations.showPopup(this._flyoutElement, { top: "0px", left: "0px", keyframe: animationKeyframe }); - }, - - _addFlyoutIMEPaddingIfRequired: function asb_addFlyoutIMEPaddingIfRequired() { - // Check if we have InputContext APIs - var context = this._tryGetInputContext(); - if (!context) { - return; - } - - // Check if flyout is visible and below input - if (!this._isFlyoutShown() || !this._flyoutBelowInput) { - return; - } - - // Check if IME is occluding flyout - var flyoutRect = this._flyoutElement.getBoundingClientRect(); - var imeRect = context.getCandidateWindowClientRect(); - var inputRect = this._inputElement.getBoundingClientRect(); - var flyoutTop = inputRect.bottom; - var flyoutBottom = inputRect.bottom + flyoutRect.height; - if (imeRect.top > flyoutBottom || imeRect.bottom < flyoutTop) { - return; - } - - // Shift the flyout down or to the right depending on IME/ASB width ratio. - // When the IME width is less than 45% of the ASB's width, the flyout gets - // shifted right, otherwise shifted down. - var animation = Animations.createRepositionAnimation(this._flyoutElement); - if (imeRect.width < (inputRect.width * 0.45)) { - this._flyoutElement.style.marginLeft = imeRect.width + "px"; - } else { - this._flyoutElement.style.marginTop = (imeRect.bottom - imeRect.top + 4) + "px"; - } - animation.execute(); - }, - - _findNextSuggestionElementIndex: function asb_findNextSuggestionElementIndex(curIndex) { - // Returns -1 if there are no focusable elements after curIndex - // Returns first element if curIndex < 0 - var startIndex = curIndex < 0 ? 0 : curIndex + 1; - for (var i = startIndex; i < this._suggestionsData.length; i++) { - if ((this._repeater.elementFromIndex(i)) && (this._isSuggestionSelectable(this._suggestionsData.getAt(i)))) { - return i; - } - } - return -1; - }, - - _findPreviousSuggestionElementIndex: function asb_findPreviousSuggestionElementIndex(curIndex) { - // Returns -1 if there are no focusable elements before curIndex - // Returns last element if curIndex >= suggestionsdata.length - var startIndex = curIndex >= this._suggestionsData.length ? this._suggestionsData.length - 1 : curIndex - 1; - for (var i = startIndex; i >= 0; i--) { - if ((this._repeater.elementFromIndex(i)) && (this._isSuggestionSelectable(this._suggestionsData.getAt(i)))) { - return i; - } - } - return -1; - }, - - _isFlyoutShown: function asb_isFlyoutShown() { - return (this._flyoutElement.style.display !== "none"); - }, - - _isSuggestionSelectable: function asb_isSuggestionSelectable(suggestion) { - return ((suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Query) || - (suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Result)); - }, - - _processSuggestionChosen: function asb_processSuggestionChosen(item, event) { - this.queryText = item.text; - if (item.kind === _SuggestionManagerShim._SearchSuggestionKind.Query) { - this._submitQuery(item.text, false /*fillLinguisticDetails*/, event); // force empty linguistic details since explicitly chosen suggestion from list - } else if (item.kind === _SuggestionManagerShim._SearchSuggestionKind.Result) { - this._fireEvent(EventNames.resultsuggestionchosen, { - tag: item.tag, - keyModifiers: getKeyModifiers(event), - storageFile: null - }); - } - this._hideFlyout(); - }, - - _selectSuggestionAtIndex: function asb_selectSuggestionAtIndex(indexToSelect) { - var that = this; - function scrollToView(targetElement) { - var popupHeight = that._flyoutElement.getBoundingClientRect().bottom - that._flyoutElement.getBoundingClientRect().top; - if ((targetElement.offsetTop + targetElement.offsetHeight) > (that._flyoutElement.scrollTop + popupHeight)) { - // Element to scroll is below popup visible area - var scrollDifference = (targetElement.offsetTop + targetElement.offsetHeight) - (that._flyoutElement.scrollTop + popupHeight); - _ElementUtilities._zoomTo(that._flyoutElement, { contentX: 0, contentY: (that._flyoutElement.scrollTop + scrollDifference), viewportX: 0, viewportY: 0 }); - } else if (targetElement.offsetTop < that._flyoutElement.scrollTop) { - // Element to scroll is above popup visible area - _ElementUtilities._zoomTo(that._flyoutElement, { contentX: 0, contentY: targetElement.offsetTop, viewportX: 0, viewportY: 0 }); - } - } - - // Sets focus on the specified element and removes focus from others. - // Clears selection if index is outside of suggestiondata index range. - var curElement = null; - for (var i = 0; i < this._suggestionsData.length; i++) { - curElement = this._repeater.elementFromIndex(i); - if (i !== indexToSelect) { - curElement.classList.remove(ClassNames.asbSuggestionSelected); - curElement.setAttribute("aria-selected", "false"); - } else { - curElement.classList.add(ClassNames.asbSuggestionSelected); - scrollToView(curElement); - curElement.setAttribute("aria-selected", "true"); - } - } - this._currentSelectedIndex = indexToSelect; - if (curElement) { - this._inputElement.setAttribute("aria-activedescendant", this._repeaterElement.id + indexToSelect); - } else if (this._inputElement.hasAttribute("aria-activedescendant")) { - this._inputElement.removeAttribute("aria-activedescendant"); - } - }, - - _updateFakeFocus: function asb_updateFakeFocus() { - var firstElementIndex; - if (this._isFlyoutShown() && (this._chooseSuggestionOnEnter)) { - firstElementIndex = this._findNextSuggestionElementIndex(-1); - } else { - // This will clear the fake focus. - firstElementIndex = -1; - } - - this._selectSuggestionAtIndex(firstElementIndex); - }, - - _updateQueryTextWithSuggestionText: function asb_updateQueryTextWithSuggestionText(suggestionIndex) { - if ((suggestionIndex >= 0) && (suggestionIndex < this._suggestionsData.length)) { - this.queryText = this._suggestionsData.getAt(suggestionIndex).text; - } - }, - - // Helpers - _disableControl: function asb_disableControl() { - if (this._isFlyoutShown()) { - this._hideFlyout(); - } - this._element.disabled = true; - this._element.classList.add(ClassNames.asbDisabled); - this._inputElement.disabled = true; - }, - - _enableControl: function asb_enableControl() { - this._element.disabled = false; - this._element.classList.remove(ClassNames.asbDisabled); - this._inputElement.disabled = false; - if (_Global.document.activeElement === this._element) { - _ElementUtilities._setActive(this._inputElement); - } - }, - - _fireEvent: function asb_fireEvent(type, detail) { - // Returns true if ev.preventDefault() was not called - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(type, true, true, detail); - return this._element.dispatchEvent(event); - }, - - _getLinguisticDetails: function asb_getLinguisticDetails(useCache, createFilled) { // createFilled=false always creates an empty linguistic details object, otherwise generate it or use the cache - function createQueryLinguisticDetails(compositionAlternatives, compositionStartOffset, compositionLength, queryTextPrefix, queryTextSuffix) { - var linguisticDetails = null; - - // The linguistic alternatives we receive are only for the composition string being composed. We need to provide the linguistic alternatives - // in the form of the full query text with alternatives embedded. - var fullCompositionAlternatives = []; - for (var i = 0; i < compositionAlternatives.length; i++) { - fullCompositionAlternatives[i] = queryTextPrefix + compositionAlternatives[i] + queryTextSuffix; - } - - if (_WinRT.Windows.ApplicationModel.Search.SearchQueryLinguisticDetails) { - try { - linguisticDetails = new _WinRT.Windows.ApplicationModel.Search.SearchQueryLinguisticDetails(fullCompositionAlternatives, compositionStartOffset, compositionLength); - } catch (e) { - // WP10 currently exposes SQLD API but throws on instantiation. - } - } - - if (!linguisticDetails) { - // If we're in web compartment, create a script version of the WinRT SearchQueryLinguisticDetails object - linguisticDetails = { - queryTextAlternatives: fullCompositionAlternatives, - queryTextCompositionStart: compositionStartOffset, - queryTextCompositionLength: compositionLength - }; - } - return linguisticDetails; - } - - var linguisticDetails = null; - if ((this._inputElement.value === this._prevQueryText) && useCache && this._prevLinguisticDetails && createFilled) { - linguisticDetails = this._prevLinguisticDetails; - } else { - var compositionAlternatives = []; - var compositionStartOffset = 0; - var compositionLength = 0; - var queryTextPrefix = ""; - var queryTextSuffix = ""; - if (createFilled) { - var context = this._tryGetInputContext(); - if (context && context.getCompositionAlternatives) { - compositionAlternatives = context.getCompositionAlternatives(); - compositionStartOffset = context.compositionStartOffset; - compositionLength = context.compositionEndOffset - context.compositionStartOffset; - - if ((this._inputElement.value !== this._prevQueryText) || (this._prevCompositionLength === 0) || (compositionLength > 0)) { - queryTextPrefix = this._inputElement.value.substring(0, compositionStartOffset); - queryTextSuffix = this._inputElement.value.substring(compositionStartOffset + compositionLength); - } else { - // composition ended, but alternatives have been kept, need to reuse the previous query prefix/suffix, but still report to the client that the composition has ended (start & length of composition of 0) - queryTextPrefix = this._inputElement.value.substring(0, this._prevCompositionStart); - queryTextSuffix = this._inputElement.value.substring(this._prevCompositionStart + this._prevCompositionLength); - } - } - } - linguisticDetails = createQueryLinguisticDetails(compositionAlternatives, compositionStartOffset, compositionLength, queryTextPrefix, queryTextSuffix); - } - return linguisticDetails; - }, - - _isElementInSearchControl: function asb_isElementInSearchControl(targetElement) { - return this.element.contains(targetElement) || (this.element === targetElement); - }, - - _renderSuggestion: function asb_renderSuggestion(suggestion) { - var root = null; - if (!suggestion) { - return root; - } - if (suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Query) { - root = querySuggestionRenderer(this, suggestion); - } else if (suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Separator) { - root = separatorSuggestionRenderer(suggestion); - } else if (suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Result) { - root = resultSuggestionRenderer(this, suggestion); - } else { - throw new _ErrorFromName("WinJS.UI.AutoSuggestBox.invalidSuggestionKind", Strings.invalidSuggestionKind); - } - return root; - }, - - _shouldIgnoreInput: function asb_shouldIgnoreInput() { - var processingIMEFocusLossKey = this._isProcessingDownKey || this._isProcessingUpKey || this._isProcessingTabKey || this._isProcessingEnterKey; - return processingIMEFocusLossKey || this._isFlyoutPointerDown; - }, - - _submitQuery: function asb_submitQuery(queryText, fillLinguisticDetails, event) { - if (this._disposed) { - return; - } - - // get the most up to date value of the input langauge from WinRT if available - if (_WinRT.Windows.Globalization.Language) { - this._lastKeyPressLanguage = _WinRT.Windows.Globalization.Language.currentInputMethodLanguageTag; - } - - this._fireEvent(EventNames.querysubmitted, { - language: this._lastKeyPressLanguage, - linguisticDetails: this._getLinguisticDetails(true /*useCache*/, fillLinguisticDetails), // allow caching, but generate empty linguistic details if suggestion is used - queryText: queryText, - keyModifiers: getKeyModifiers(event) - }); - - if (this._suggestionManager) { - this._suggestionManager.addToHistory(this._inputElement.value, this._lastKeyPressLanguage); - } - }, - - _tryGetInputContext: function asb_tryGetInputContext() { - // On WP, msGetInputContext is defined but throws when invoked - if (this._inputElement.msGetInputContext) { - try { - return this._inputElement.msGetInputContext(); - } catch (e) { - return null; - } - } - return null; - }, - - _updateInputElementAriaLabel: function asb_updateInputElementAriaLabel() { - this._inputElement.setAttribute("aria-label", - this._inputElement.placeholder ? _Resources._formatString(Strings.ariaLabelInputPlaceHolder, this._inputElement.placeholder) : Strings.ariaLabelInputNoPlaceHolder - ); - }, - - // Event Handlers - _flyoutBlurHandler: function asb_flyoutBlurHandler(event) { - if (this._isElementInSearchControl(_Global.document.activeElement)) { - this._internalFocusMove = true; - } else { - this._element.classList.remove(ClassNames.asbInputFocus); - this._hideFlyout(); - } - }, - - _flyoutPointerDownHandler: function asb_flyoutPointerDownHandler(ev) { - var that = this; - var srcElement = ev.target; - function findSuggestionElementIndex() { - if (srcElement) { - for (var i = 0; i < that._suggestionsData.length; i++) { - if (that._repeater.elementFromIndex(i) === srcElement) { - return i; - } - } - } - return -1; - } - - this._isFlyoutPointerDown = true; - while (srcElement && (srcElement.parentNode !== this._repeaterElement)) { - srcElement = srcElement.parentNode; - } - var index = findSuggestionElementIndex(); - if ((index >= 0) && (index < this._suggestionsData.length) && (this._currentFocusedIndex !== index)) { - if (this._isSuggestionSelectable(this._suggestionsData.getAt(index))) { - this._currentFocusedIndex = index; - this._selectSuggestionAtIndex(index); - this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); - } - } - // Prevent default so focus does not leave input element. - ev.preventDefault(); - }, - - _flyoutPointerReleasedHandler: function asb_flyoutPointerReleasedHandler() { - this._isFlyoutPointerDown = false; - - if (this._reflowImeOnPointerRelease) { - this._reflowImeOnPointerRelease = false; - var animation = Animations.createRepositionAnimation(this._flyoutElement); - this._flyoutElement.style.marginTop = ""; - this._flyoutElement.style.marginLeft = ""; - animation.execute(); - } - }, - - _inputBlurHandler: function asb_inputBlurHandler(event) { - // Hide flyout if focus is leaving the control - if (!this._isElementInSearchControl(_Global.document.activeElement)) { - this._element.classList.remove(ClassNames.asbInputFocus); - this._hideFlyout(); - } - this.queryText = this._prevQueryText; // Finalize IME composition - this._isProcessingDownKey = false; - this._isProcessingUpKey = false; - this._isProcessingTabKey = false; - this._isProcessingEnterKey = false; - }, - - _inputFocusHandler: function asb_inputFocusHandler(event) { - // Refresh hit highlighting if text has changed since focus was present - // This can happen if the user committed a suggestion previously. - if (this._inputElement.value !== this._prevQueryText) { - if (_WinRT.Windows.Data.Text.SemanticTextQuery) { - if (this._inputElement.value !== "") { - this._hitFinder = new _WinRT.Windows.Data.Text.SemanticTextQuery(this._inputElement.value, this._inputElement.lang); - } else { - this._hitFinder = null; - } - } - } - - // If focus is returning to the input box from outside the control, show the flyout and refresh the suggestions - if (event.target === this._inputElement && !this._internalFocusMove) { - this._showFlyout(); - if (this._currentFocusedIndex !== -1) { - // Focus is not in input - this._selectSuggestionAtIndex(this._currentFocusedIndex); - } else { - this._updateFakeFocus(); - } - - this._suggestionManager.setQuery( - this._inputElement.value, - this._lastKeyPressLanguage, - this._getLinguisticDetails(true /*useCache*/, true /*createFilled*/) - ); - } - - this._internalFocusMove = false; - this._element.classList.add(ClassNames.asbInputFocus); - }, - - _inputOrImeChangeHandler: function asb_inputImeChangeHandler() { - var that = this; - function hasLinguisticDetailsChanged(newLinguisticDetails) { - var hasLinguisticDetailsChanged = false; - if ((that._prevLinguisticDetails.queryTextCompositionStart !== newLinguisticDetails.queryTextCompositionStart) || - (that._prevLinguisticDetails.queryTextCompositionLength !== newLinguisticDetails.queryTextCompositionLength) || - (that._prevLinguisticDetails.queryTextAlternatives.length !== newLinguisticDetails.queryTextAlternatives.length)) { - hasLinguisticDetailsChanged = true; - } - that._prevLinguisticDetails = newLinguisticDetails; - return hasLinguisticDetailsChanged; - } - - // swallow the IME change event that gets fired when composition is ended due to keyboarding down to the suggestion list & mouse down on the button - if (!this._shouldIgnoreInput()) { - var linguisticDetails = this._getLinguisticDetails(false /*useCache*/, true /*createFilled*/); // never cache on explicit user changes - var hasLinguisticDetailsChanged = hasLinguisticDetailsChanged(linguisticDetails); // updates this._prevLinguisticDetails - - // Keep the previous composition cache up to date, execpt when composition ended with no text change and alternatives are kept. - // In that case, we need to use the cached values to correctly generate the query prefix/suffix for substituting alternatives, but still report to the client that the composition has ended (via start & length of composition of 0) - if ((this._inputElement.value !== this._prevQueryText) || (this._prevCompositionLength === 0) || (linguisticDetails.queryTextCompositionLength > 0)) { - this._prevCompositionStart = linguisticDetails.queryTextCompositionStart; - this._prevCompositionLength = linguisticDetails.queryTextCompositionLength; - } - - if ((this._prevQueryText === this._inputElement.value) && !hasLinguisticDetailsChanged) { - // Sometimes the input change is fired even if there is no change in input. - // Swallow event in those cases. - return; - } - this._prevQueryText = this._inputElement.value; - - // get the most up to date value of the input langauge from WinRT if available - if (_WinRT.Windows.Globalization.Language) { - this._lastKeyPressLanguage = _WinRT.Windows.Globalization.Language.currentInputMethodLanguageTag; - } - - if (_WinRT.Windows.Data.Text.SemanticTextQuery) { - if (this._inputElement.value !== "") { - this._hitFinder = new _WinRT.Windows.Data.Text.SemanticTextQuery(this._inputElement.value, this._lastKeyPressLanguage); - } else { - this._hitFinder = null; - } - } - - this._fireEvent(EventNames.querychanged, { - language: this._lastKeyPressLanguage, - queryText: this._inputElement.value, - linguisticDetails: linguisticDetails - }); - - this._suggestionManager.setQuery( - this._inputElement.value, - this._lastKeyPressLanguage, - linguisticDetails - ); - } - }, - - _inputPointerDownHandler: function asb_inputPointerDownHandler() { - if ((_Global.document.activeElement === this._inputElement) && (this._currentSelectedIndex !== -1)) { - this._currentFocusedIndex = -1; - this._selectSuggestionAtIndex(this._currentFocusedIndex); - } - }, - - _keyDownHandler: function asb_keyDownHandler(event) { - var that = this; - function setSelection(index) { - that._currentFocusedIndex = index; - that._selectSuggestionAtIndex(index); - event.preventDefault(); - event.stopPropagation(); - } - - this._lastKeyPressLanguage = event.locale; - if (event.keyCode === Key.tab) { - this._isProcessingTabKey = true; - } else if (event.keyCode === Key.upArrow) { - this._isProcessingUpKey = true; - } else if (event.keyCode === Key.downArrow) { - this._isProcessingDownKey = true; - } else if ((event.keyCode === Key.enter) && (event.locale === "ko")) { - this._isProcessingEnterKey = true; - } - // Ignore keys handled by ime. - if (event.keyCode !== Key.IME) { - if (event.keyCode === Key.tab) { - var closeFlyout = true; - if (event.shiftKey) { - if (this._currentFocusedIndex !== -1) { - // Focus is not in input - setSelection(-1); - closeFlyout = false; - } - } else if (this._currentFocusedIndex === -1) { - this._currentFocusedIndex = - this._flyoutBelowInput - ? this._findNextSuggestionElementIndex(this._currentFocusedIndex) - : this._findPreviousSuggestionElementIndex(this._suggestionsData.length); - if (this._currentFocusedIndex !== -1) { - // Found a selectable element - setSelection(this._currentFocusedIndex); - this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); - closeFlyout = false; - } - } - - if (closeFlyout) { - this._hideFlyout(); - } - } else if (event.keyCode === Key.escape) { - if (this._currentFocusedIndex !== -1) { - // Focus is not in input - this.queryText = this._prevQueryText; - setSelection(-1); - } else if (this.queryText !== "") { - this.queryText = ""; - this._inputOrImeChangeHandler(null); - event.preventDefault(); - event.stopPropagation(); - } - } else if ((this._flyoutBelowInput && event.keyCode === Key.upArrow) || (!this._flyoutBelowInput && event.keyCode === Key.downArrow)) { - var prevIndex; - if (this._currentSelectedIndex !== -1) { - prevIndex = this._findPreviousSuggestionElementIndex(this._currentSelectedIndex); - // Restore user entered query when user navigates back to input. - if (prevIndex === -1) { - this.queryText = this._prevQueryText; - } - } else { - prevIndex = this._findPreviousSuggestionElementIndex(this._suggestionsData.length); - } - setSelection(prevIndex); - this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); - } else if ((this._flyoutBelowInput && event.keyCode === Key.downArrow) || (!this._flyoutBelowInput && event.keyCode === Key.upArrow)) { - var nextIndex = this._findNextSuggestionElementIndex(this._currentSelectedIndex); - // Restore user entered query when user navigates back to input. - if ((this._currentSelectedIndex !== -1) && (nextIndex === -1)) { - this.queryText = this._prevQueryText; - } - setSelection(nextIndex); - this._updateQueryTextWithSuggestionText(this._currentFocusedIndex); - } else if (event.keyCode === Key.enter) { - if (this._currentSelectedIndex === -1) { - this._submitQuery(this._inputElement.value, true /*fillLinguisticDetails*/, event); - } else { - this._processSuggestionChosen(this._suggestionsData.getAt(this._currentSelectedIndex), event); - } - this._hideFlyout(); - } - } - }, - - _keyUpHandler: function asb_keyUpHandler(event) { - if (event.keyCode === Key.tab) { - this._isProcessingTabKey = false; - } else if (event.keyCode === Key.upArrow) { - this._isProcessingUpKey = false; - } else if (event.keyCode === Key.downArrow) { - this._isProcessingDownKey = false; - } else if (event.keyCode === Key.enter) { - this._isProcessingEnterKey = false; - } - }, - - _keyPressHandler: function asb_keyPressHandler(event) { - this._lastKeyPressLanguage = event.locale; - }, - - _msCandidateWindowHideHandler: function asb_msCandidateWindowHideHandler() { - if (!this._isFlyoutPointerDown) { - var animation = Animations.createRepositionAnimation(this._flyoutElement); - this._flyoutElement.style.marginTop = ""; - this._flyoutElement.style.marginLeft = ""; - animation.execute(); - } else { - this._reflowImeOnPointerRelease = true; - } - }, - - _msCandidateWindowShowHandler: function asb_msCandidateWindowShowHandler() { - this._addFlyoutIMEPaddingIfRequired(); - this._reflowImeOnPointerRelease = false; - }, - - _suggestionsChangedHandler: function asb_suggestionsChangedHandler(event) { - var collectionChange = event.collectionChange || event.detail.collectionChange; - var changeIndex = (+event.index === event.index) ? event.index : event.detail.index; - var ChangeEnum = _SuggestionManagerShim._CollectionChange; - if (collectionChange === ChangeEnum.reset) { - if (this._isFlyoutShown()) { - this._hideFlyout(); - } - this._suggestionsData.splice(0, this._suggestionsData.length); - } else if (collectionChange === ChangeEnum.itemInserted) { - var suggestion = this._suggestions[changeIndex]; - this._suggestionsData.splice(changeIndex, 0, suggestion); - - this._showFlyout(); - - } else if (collectionChange === ChangeEnum.itemRemoved) { - if ((this._suggestionsData.length === 1)) { - _ElementUtilities._setActive(this._inputElement); - - this._hideFlyout(); - } - this._suggestionsData.splice(changeIndex, 1); - } else if (collectionChange === ChangeEnum.itemChanged) { - var suggestion = this._suggestions[changeIndex]; - if (suggestion !== this._suggestionsData.getAt(changeIndex)) { - this._suggestionsData.setAt(changeIndex, suggestion); - } else { - // If the suggestions manager gives us an identical item, it means that only the hit highlighted text has changed. - var existingElement = this._repeater.elementFromIndex(changeIndex); - if (_ElementUtilities.hasClass(existingElement, ClassNames.asbSuggestionQuery)) { - addHitHighlightedText(existingElement, suggestion, suggestion.text); - } else { - var resultSuggestionDiv = existingElement.querySelector("." + ClassNames.asbSuggestionResultText); - if (resultSuggestionDiv) { - addHitHighlightedText(resultSuggestionDiv, suggestion, suggestion.text); - var resultSuggestionDetailDiv = existingElement.querySelector("." + ClassNames.asbSuggestionResultDetailedText); - if (resultSuggestionDetailDiv) { - addHitHighlightedText(resultSuggestionDetailDiv, suggestion, suggestion.detailText); - } - } - } - } - } - - if (_Global.document.activeElement === this._inputElement) { - this._updateFakeFocus(); - } - }, - - _suggestionsRequestedHandler: function asb_suggestionsRequestedHandler(event) { - // get the most up to date value of the input langauge from WinRT if available - if (_WinRT.Windows.Globalization.Language) { - this._lastKeyPressLanguage = _WinRT.Windows.Globalization.Language.currentInputMethodLanguageTag; - } - - var request = event.request || event.detail.request; - var deferral; - this._fireEvent(EventNames.suggestionsrequested, { - setPromise: function (promise) { - deferral = request.getDeferral(); - promise.then(function () { - deferral.complete(); - }); - }, - searchSuggestionCollection: request.searchSuggestionCollection, - language: this._lastKeyPressLanguage, - linguisticDetails: this._getLinguisticDetails(true /*useCache*/, true /*createFilled*/), - queryText: this._inputElement.value - }); - }, - }, { - createResultSuggestionImage: function asb_createResultSuggestionImage(url) { - /// - /// - /// Creates the image argument for SearchSuggestionCollection.appendResultSuggestion. - /// - /// - /// The url of the image. - /// - /// - /// - if (_WinRT.Windows.Foundation.Uri && _WinRT.Windows.Storage.Streams.RandomAccessStreamReference) { - return _WinRT.Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(new _WinRT.Windows.Foundation.Uri(url)); - } - return url; - }, - - _EventNames: EventNames, - - _sortAndMergeHits: function asb_sortAndMergeHits(hitsProvided) { - function hitStartPositionAscendingSorter(firstHit, secondHit) { - var returnValue = 0; - if (firstHit.startPosition < secondHit.startPosition) { - returnValue = -1; - } else if (firstHit.startPosition > secondHit.startPosition) { - returnValue = 1; - } - return returnValue; - } - function hitIntersectionReducer(reducedHits, nextHit, currentIndex) { - if (currentIndex === 0) { - reducedHits.push(nextHit); - } else { - var curHit = reducedHits[reducedHits.length - 1]; - var curHitEndPosition = curHit.startPosition + curHit.length; - if (nextHit.startPosition <= curHitEndPosition) { - // The next hit intersects or is next to current hit. Merge it. - var nextHitEndPosition = nextHit.startPosition + nextHit.length; - if (nextHitEndPosition > curHitEndPosition) { - curHit.length = nextHitEndPosition - curHit.startPosition; - } - } else { - // No intersection, simply add to reduced list. - reducedHits.push(nextHit); - } - } - return reducedHits; - } - - var reducedHits = []; - if (hitsProvided) { - // Copy hitsprovided array as winrt objects are immutable. - var hits = new Array(hitsProvided.length); - for (var i = 0; i < hitsProvided.length; i++) { - hits.push({ startPosition: hitsProvided[i].startPosition, length: hitsProvided[i].length }); - } - hits.sort(hitStartPositionAscendingSorter); - hits.reduce(hitIntersectionReducer, reducedHits); - } - return reducedHits; - } - }); - - function addHitHighlightedText(element, item, text, hitFinder) { - function addNewSpan(element, textContent, insertBefore) { - // Adds new span element with specified inner text as child to element, placed before insertBefore - var spanElement = _Global.document.createElement("span"); - spanElement.textContent = textContent; - spanElement.setAttribute("aria-hidden", "true"); - spanElement.classList.add(ClassNames.asbHitHighlightSpan); - element.insertBefore(spanElement, insertBefore); - return spanElement; - } - - if (text) { - // Remove any existing hit highlighted text spans - _ElementListUtilities.query("." + ClassNames.asbHitHighlightSpan, element).forEach(function (childElement) { - childElement.parentNode.removeChild(childElement); - }); - - // Insert spans at the front of element - var firstChild = element.firstChild; - - var hitsProvided = item.hits; - if ((!hitsProvided) && (hitFinder) && (item.kind !== _SuggestionManagerShim._SearchSuggestionKind.Separator)) { - hitsProvided = hitFinder.find(text); - } - - var hits = AutoSuggestBox._sortAndMergeHits(hitsProvided); - - var lastPosition = 0; - for (var i = 0; i < hits.length; i++) { - var hit = hits[i]; - - // Add previous normal text - addNewSpan(element, text.substring(lastPosition, hit.startPosition), firstChild); - - lastPosition = hit.startPosition + hit.length; - - // Add hit highlighted text - var spanHitHighlightedText = addNewSpan(element, text.substring(hit.startPosition, lastPosition), firstChild); - _ElementUtilities.addClass(spanHitHighlightedText, ClassNames.asbBoxFlyoutHighlightText); - } - - // Add final normal text - if (lastPosition < text.length) { - addNewSpan(element, text.substring(lastPosition), firstChild); - } - } - } - - function getKeyModifiers(ev) { - // Returns the same value as https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.system.virtualkeymodifiers - var VirtualKeys = { - ctrlKey: 1, - altKey: 2, - shiftKey: 4 - }; - - var keyModifiers = 0; - if (ev.ctrlKey) { - keyModifiers |= VirtualKeys.ctrlKey; - } - if (ev.altKey) { - keyModifiers |= VirtualKeys.altKey; - } - if (ev.shiftKey) { - keyModifiers |= VirtualKeys.shiftKey; - } - return keyModifiers; - } - - function resultSuggestionRenderer(asb, item) { - function handleInvoke(e) { - asb._internalFocusMove = true; - asb._inputElement.focus(); - asb._processSuggestionChosen(item, e); - } - - var root = _Global.document.createElement("div"); - var image = new _Global.Image(); - image.style.opacity = 0; - var loadImage = function (url) { - function onload() { - image.removeEventListener("load", onload, false); - Animations.fadeIn(image); - } - image.addEventListener("load", onload, false); - image.src = url; - }; - - if (item.image !== null) { - item.image.openReadAsync().then(function (streamWithContentType) { - if (streamWithContentType !== null) { - loadImage(_Global.URL.createObjectURL(streamWithContentType, { oneTimeOnly: true })); - } - }); - } else if (item.imageUrl !== null) { - loadImage(item.imageUrl); - } - image.setAttribute("aria-hidden", "true"); - root.appendChild(image); - - var divElement = _Global.document.createElement("div"); - _ElementUtilities.addClass(divElement, ClassNames.asbSuggestionResultText); - addHitHighlightedText(divElement, item, item.text); - divElement.title = item.text; - divElement.setAttribute("aria-hidden", "true"); - root.appendChild(divElement); - - var brElement = _Global.document.createElement("br"); - divElement.appendChild(brElement); - - var divDetailElement = _Global.document.createElement("span"); - _ElementUtilities.addClass(divDetailElement, ClassNames.asbSuggestionResultDetailedText); - addHitHighlightedText(divDetailElement, item, item.detailText); - divDetailElement.title = item.detailText; - divDetailElement.setAttribute("aria-hidden", "true"); - divElement.appendChild(divDetailElement); - - _ElementUtilities.addClass(root, ClassNames.asbSuggestionResult); - - _ElementUtilities._addEventListener(root, "click", function (e) { - if (!asb._isFlyoutPointerDown) { - handleInvoke(e); - } - }); - _ElementUtilities._addEventListener(root, "pointerup", handleInvoke); - - root.setAttribute("role", "option"); - var ariaLabel = _Resources._formatString(Strings.ariaLabelResult, item.text, item.detailText); - root.setAttribute("aria-label", ariaLabel); - return root; - } - - function querySuggestionRenderer(asb, item) { - function handleInvoke(e) { - asb._internalFocusMove = true; - asb._inputElement.focus(); - asb._processSuggestionChosen(item, e); - } - - var root = _Global.document.createElement("div"); - - addHitHighlightedText(root, item, item.text); - root.title = item.text; - - root.classList.add(ClassNames.asbSuggestionQuery); - - _ElementUtilities._addEventListener(root, "click", function (e) { - if (!asb._isFlyoutPointerDown) { - handleInvoke(e); - } - }); - _ElementUtilities._addEventListener(root, "pointerup", handleInvoke); - - var ariaLabel = _Resources._formatString(Strings.ariaLabelQuery, item.text); - root.setAttribute("role", "option"); - root.setAttribute("aria-label", ariaLabel); - - return root; - } - - function separatorSuggestionRenderer(item) { - var root = _Global.document.createElement("div"); - if (item.text.length > 0) { - var textElement = _Global.document.createElement("div"); - textElement.textContent = item.text; - textElement.title = item.text; - textElement.setAttribute("aria-hidden", "true"); - root.appendChild(textElement); - } - root.insertAdjacentHTML("beforeend", "
"); - _ElementUtilities.addClass(root, ClassNames.asbSuggestionSeparator); - root.setAttribute("role", "separator"); - var ariaLabel = _Resources._formatString(Strings.ariaLabelSeparator, item.text); - root.setAttribute("aria-label", ariaLabel); - return root; - } - - _Base.Class.mix(AutoSuggestBox, _Control.DOMEventMixin); - return AutoSuggestBox; - }) - }); - exports.ClassNames = ClassNames; -}); - - -define('require-style!less/styles-searchbox',[],function(){}); - -define('require-style!less/colors-searchbox',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/SearchBox',[ - '../Core/_Global', - '../Core/_WinRT', - '../Core/_Base', - '../Core/_ErrorFromName', - '../Core/_Events', - '../Core/_Resources', - './AutoSuggestBox', - '../_Accents', - '../Utilities/_Control', - '../Utilities/_ElementUtilities', - './AutoSuggestBox/_SearchSuggestionManagerShim', - '../Application', - 'require-style!less/styles-searchbox', - 'require-style!less/colors-searchbox' -], function searchboxInit(_Global, _WinRT, _Base, _ErrorFromName, _Events, _Resources, AutoSuggestBox, _Accents, _Control, _ElementUtilities, _SuggestionManagerShim, Application) { - "use strict"; - - _Accents.createAccentRule("html.win-hoverable .win-searchbox-button:not(.win-searchbox-button-disabled):hover", [{ name: "color", value: _Accents.ColorTypes.accent }, ]); - _Accents.createAccentRule(".win-searchbox-button.win-searchbox-button:not(.win-searchbox-button-disabled):hover:active", [{ name: "background-color", value: _Accents.ColorTypes.accent }, ]); - - _Base.Namespace.define("WinJS.UI", { - /// - /// - /// Enables the user to perform search queries and select suggestions. - /// - /// - /// - /// - /// - /// ]]> - /// - /// Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. - /// - /// Styles the entire Search box control. - /// Styles the query input box. - /// Styles the search button. - /// Styles the result suggestions flyout. - /// Styles the result type suggestion. - /// Styles the query type suggestion. - /// - /// Styles the separator type suggestion. - /// - /// - /// Styles the currently selected suggestion. - /// - /// - /// - SearchBox: _Base.Namespace._lazy(function () { - - // Enums - var ClassName = { - searchBox: "win-searchbox", - searchBoxDisabled: "win-searchbox-disabled", - searchBoxInput: "win-searchbox-input", - searchBoxInputFocus: "win-searchbox-input-focus", - searchBoxButton: "win-searchbox-button", - searchBoxFlyout: "win-searchbox-flyout", - searchBoxFlyoutHighlightText: "win-searchbox-flyout-highlighttext", - searchBoxHitHighlightSpan: "win-searchbox-hithighlight-span", - searchBoxSuggestionResult: "win-searchbox-suggestion-result", - searchBoxSuggestionResultText: "win-searchbox-suggestion-result-text", - searchBoxSuggestionResultDetailedText: "win-searchbox-suggestion-result-detailed-text", - searchBoxSuggestionSelected: "win-searchbox-suggestion-selected", - searchBoxSuggestionQuery: "win-searchbox-suggestion-query", - searchBoxSuggestionSeparator: "win-searchbox-suggestion-separator", - searchBoxButtonInputFocus: "win-searchbox-button-input-focus", - searchBoxButtonDisabled: "win-searchbox-button-disabled" - }; - - var EventName = { - receivingfocusonkeyboardinput: "receivingfocusonkeyboardinput" - }; - - var strings = { - get invalidSearchBoxSuggestionKind() { return "Error: Invalid search suggestion kind."; }, - get ariaLabel() { return _Resources._getWinJSString("ui/searchBoxAriaLabel").value; }, - get ariaLabelInputNoPlaceHolder() { return _Resources._getWinJSString("ui/searchBoxAriaLabelInputNoPlaceHolder").value; }, - get ariaLabelInputPlaceHolder() { return _Resources._getWinJSString("ui/searchBoxAriaLabelInputPlaceHolder").value; }, - get searchBoxDeprecated() { return "SearchBox is deprecated and may not be available in future releases. Instead use AutoSuggestBox."; } - }; - - var SearchBox = _Base.Class.derive(AutoSuggestBox.AutoSuggestBox, function SearchBox_ctor(element, options) { - /// - /// - /// Creates a new SearchBox. - /// - /// - /// The DOM element that hosts the SearchBox. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". For example, to provide a handler for the querychanged event, - /// add a property named "onquerychanged" to the options object and set its value to the event handler. - /// This parameter is optional. - /// - /// - /// The new SearchBox. - /// - /// - /// SearchBox is deprecated and may not be available in future releases. Instead use AutoSuggestBox. - /// - /// - /// - - _ElementUtilities._deprecated(strings.searchBoxDeprecated); - - this._requestingFocusOnKeyboardInputHandlerBind = this._requestingFocusOnKeyboardInputHandler.bind(this); - - // Elements - this._buttonElement = _Global.document.createElement("div"); - - // Variables - this._focusOnKeyboardInput = false; - - // Calling the super constructor - since the super constructor processes the options, - // any property setter at this point must be functional. - AutoSuggestBox.AutoSuggestBox.call(this, element, options); - - // Add SearchBox classes to DOM elements - this.element.classList.add(ClassName.searchBox); - this._flyoutElement.classList.add(ClassName.searchBoxFlyout); - - this._inputElement.classList.add(ClassName.searchBoxInput); - this._inputElement.addEventListener("blur", this._searchboxInputBlurHandler.bind(this)); - this._inputElement.addEventListener("focus", this._searchboxInputFocusHandler.bind(this)); - - this._buttonElement.tabIndex = -1; - this._buttonElement.classList.add(ClassName.searchBoxButton); - this._buttonElement.addEventListener("click", this._buttonClickHandler.bind(this)); - _ElementUtilities._addEventListener(this._buttonElement, "pointerdown", this._buttonPointerDownHandler.bind(this)); - this.element.appendChild(this._buttonElement); - }, { - /// - /// Enable automatically focusing the search box when the user types into the app window (off by default) While this is enabled, - /// input on the current thread will be intercepted and redirected to the search box. Only textual input will trigger the search box to focus. - /// The caller will continue to receive non-text keys (such as arrows, tab, etc - /// This will also not affect WIN/CTRL/ALT key combinations (except for Ctrl-V for paste). - /// If the client needs more to happen than just set focus in the box (make control visible, etc.), they will need to handle the event. - /// If enabled, the app must be sure to disable this if the user puts focus in some other edit field. - /// - /// - focusOnKeyboardInput: { - get: function () { - return this._focusOnKeyboardInput; - }, - set: function (value) { - if (this._focusOnKeyboardInput && !value) { - Application._applicationListener.removeEventListener(this.element, "requestingfocusonkeyboardinput", this._requestingFocusOnKeyboardInputHandlerBind); - } else if (!this._focusOnKeyboardInput && !!value) { - Application._applicationListener.addEventListener(this.element, "requestingfocusonkeyboardinput", this._requestingFocusOnKeyboardInputHandlerBind); - } - this._focusOnKeyboardInput = !!value; - } - }, - - // Methods - dispose: function SearchBox() { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - AutoSuggestBox.AutoSuggestBox.prototype.dispose.call(this); - - if (this._focusOnKeyboardInput) { - Application._applicationListener.removeEventListener(this.element, "requestingfocusonkeyboardinput", this._requestingFocusOnKeyboardInputHandlerBind); - } - }, - - // Private methods - _disableControl: function SearchBox_disableControl() { - AutoSuggestBox.AutoSuggestBox.prototype._disableControl.call(this); - this._buttonElement.disabled = true; - this._buttonElement.classList.add(ClassName.searchBoxButtonDisabled); - this.element.classList.add(ClassName.searchBoxDisabled); - }, - - _enableControl: function SearchBox_enableControl() { - AutoSuggestBox.AutoSuggestBox.prototype._enableControl.call(this); - this._buttonElement.disabled = false; - this._buttonElement.classList.remove(ClassName.searchBoxButtonDisabled); - this.element.classList.remove(ClassName.searchBoxDisabled); - }, - - _renderSuggestion: function SearchBox_renderSuggestion(suggestion) { - // Overrides base class - var render = AutoSuggestBox.AutoSuggestBox.prototype._renderSuggestion.call(this, suggestion); - if (suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Query) { - render.classList.add(ClassName.searchBoxSuggestionQuery); - } else if (suggestion.kind === _SuggestionManagerShim._SearchSuggestionKind.Separator) { - render.classList.add(ClassName.searchBoxSuggestionSeparator); - } else { - render.classList.add(ClassName.searchBoxSuggestionResult); - - var resultText = render.querySelector("." + AutoSuggestBox.ClassNames.asbSuggestionResultText); - resultText.classList.add(ClassName.searchBoxSuggestionResultText); - - var resultDetailText = render.querySelector("." + AutoSuggestBox.ClassNames.asbSuggestionResultDetailedText); - resultDetailText.classList.add(ClassName.searchBoxSuggestionResultDetailedText); - - var spans = render.querySelectorAll("." + AutoSuggestBox.ClassNames.asbHitHighlightSpan); - for (var i = 0, len = spans.length; i < len; i++) { - spans[i].classList.add(ClassName.searchBoxHitHighlightSpan); - } - var highlightTexts = render.querySelectorAll("." + AutoSuggestBox.ClassNames.asbBoxFlyoutHighlightText); - for (var i = 0, len = highlightTexts.length; i < len; i++) { - highlightTexts[i].classList.add(ClassName.searchBoxFlyoutHighlightText); - } - } - return render; - }, - - _selectSuggestionAtIndex: function SearchBox_selectSuggestionAtIndex(indexToSelect) { - // Overrides base class - AutoSuggestBox.AutoSuggestBox.prototype._selectSuggestionAtIndex.call(this, indexToSelect); - - var currentSelected = this.element.querySelector("." + ClassName.searchBoxSuggestionSelected); - currentSelected && currentSelected.classList.remove(ClassName.searchBoxSuggestionSelected); - var newSelected = this.element.querySelector("." + AutoSuggestBox.ClassNames.asbSuggestionSelected); - newSelected && newSelected.classList.add(ClassName.searchBoxSuggestionSelected); - }, - - _shouldIgnoreInput: function SearchBox_shouldIgnoreInput() { - // Overrides base class - var shouldIgnore = AutoSuggestBox.AutoSuggestBox.prototype._shouldIgnoreInput(); - var isButtonDown = _ElementUtilities._matchesSelector(this._buttonElement, ":active"); - - return shouldIgnore || isButtonDown; - }, - - _updateInputElementAriaLabel: function SearchBox_updateInputElementAriaLabel() { - // Override base class - this._inputElement.setAttribute("aria-label", - this._inputElement.placeholder ? _Resources._formatString(strings.ariaLabelInputPlaceHolder, this._inputElement.placeholder) : strings.ariaLabelInputNoPlaceHolder - ); - }, - - // Event Handlers - _buttonPointerDownHandler: function SearchBox_buttonPointerDownHandler(e) { - this._inputElement.focus(); - e.preventDefault(); - }, - - _buttonClickHandler: function SearchBox_buttonClickHandler(event) { - this._inputElement.focus(); - this._submitQuery(this._inputElement.value, true /*fillLinguisticDetails*/, event); - this._hideFlyout(); - }, - - _searchboxInputBlurHandler: function SearchBox_inputBlurHandler() { - _ElementUtilities.removeClass(this.element, ClassName.searchBoxInputFocus); - _ElementUtilities.removeClass(this._buttonElement, ClassName.searchBoxButtonInputFocus); - }, - - _searchboxInputFocusHandler: function SearchBox_inputFocusHandler() { - _ElementUtilities.addClass(this.element, ClassName.searchBoxInputFocus); - _ElementUtilities.addClass(this._buttonElement, ClassName.searchBoxButtonInputFocus); - }, - - // Type to search helpers - _requestingFocusOnKeyboardInputHandler: function SearchBox_requestingFocusOnKeyboardInputHandler() { - this._fireEvent(EventName.receivingfocusonkeyboardinput, null); - if (_Global.document.activeElement !== this._inputElement) { - try { - this._inputElement.focus(); - } catch (e) { - } - } - } - - }, { - createResultSuggestionImage: function SearchBox_createResultSuggestionImage(url) { - /// - /// - /// Creates the image argument for SearchSuggestionCollection.appendResultSuggestion. - /// - /// - /// The url of the image. - /// - /// - /// - if (_WinRT.Windows.Foundation.Uri && _WinRT.Windows.Storage.Streams.RandomAccessStreamReference) { - return _WinRT.Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(new _WinRT.Windows.Foundation.Uri(url)); - } - return url; - }, - - _getKeyModifiers: function SearchBox_getKeyModifiers(ev) { - // Returns the same value as https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.system.virtualkeymodifiers - var VirtualKeys = { - ctrlKey: 1, - altKey: 2, - shiftKey: 4 - }; - - var keyModifiers = 0; - if (ev.ctrlKey) { - keyModifiers |= VirtualKeys.ctrlKey; - } - if (ev.altKey) { - keyModifiers |= VirtualKeys.altKey; - } - if (ev.shiftKey) { - keyModifiers |= VirtualKeys.shiftKey; - } - return keyModifiers; - }, - - _isTypeToSearchKey: function searchBox__isTypeToSearchKey(event) { - if (event.shiftKey || event.ctrlKey || event.altKey) { - return false; - } - return true; - } - }); - _Base.Class.mix(SearchBox, _Control.DOMEventMixin); - return SearchBox; - }) - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// appbar,Flyout,Flyouts,registeredforsettings,SettingsFlyout,Statics,Syriac -define('WinJS/Controls/SettingsFlyout',[ - '../Core/_Global', - '../Core/_WinRT', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_ErrorFromName', - '../Core/_Events', - '../Core/_Resources', - '../Core/_WriteProfilerMark', - '../Animations', - '../Pages', - '../Promise', - '../_LightDismissService', - '../Utilities/_Dispose', - '../Utilities/_ElementUtilities', - '../Utilities/_ElementListUtilities', - '../Utilities/_Hoverable', - './_LegacyAppBar/_Constants', - './Flyout/_Overlay' - ], function settingsFlyoutInit(_Global, _WinRT, _Base, _BaseUtils, _ErrorFromName, _Events, _Resources, _WriteProfilerMark, Animations, Pages, Promise, _LightDismissService, _Dispose, _ElementUtilities, _ElementListUtilities, _Hoverable, _Constants, _Overlay) { - "use strict"; - - _Base.Namespace.define("WinJS.UI", { - /// - /// Provides users with fast, in-context access to settings that affect the current app. - /// - /// - /// Settings Flyout - /// - /// - /// - ///
- /// - ///
Custom Settings
- ///
- ///
- /// {Your Content Here} - ///
- /// ]]>
- /// Raised just before showing a SettingsFlyout. - /// Raised immediately after a SettingsFlyout is fully shown. - /// Raised just before hiding a SettingsFlyout. - /// Raised immediately after a SettingsFlyout is fully hidden. - /// The SettingsFlyout control itself. - /// - /// - SettingsFlyout: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - var createEvent = _Events._createEventProperty; - - var settingsPageIsFocusedOnce; - - // Constants for width - var settingsNarrow = "narrow", - settingsWide = "wide"; - - // Determine if the settings pane (system language) is RTL or not. - function _shouldAnimateFromLeft() { - if (_WinRT.Windows.UI.ApplicationSettings.SettingsEdgeLocation) { - var appSettings = _WinRT.Windows.UI.ApplicationSettings; - return (appSettings.SettingsPane.edge === appSettings.SettingsEdgeLocation.left); - } else { - return false; - } - } - - // Get the settings control by matching the settingsCommandId - // if no match we'll try to match element id - function _getChildSettingsControl(parentElement, id) { - var settingElements = parentElement.querySelectorAll("." + _Constants.settingsFlyoutClass); - var retValue, - control; - for (var i = 0; i < settingElements.length; i++) { - control = settingElements[i].winControl; - if (control) { - if (control.settingsCommandId === id) { - retValue = control; - break; - } - if (settingElements[i].id === id) { - retValue = retValue || control; - } - } - } - - return retValue; - } - - var SettingsFlyout = _Base.Class.derive(_Overlay._Overlay, function SettingsFlyout_ctor(element, options) { - /// - /// Creates a new SettingsFlyout control. - /// - /// The DOM element that will host the control. - /// - /// - /// The set of properties and values to apply to the new SettingsFlyout. - /// - /// The new SettingsFlyout control. - /// - /// SettingsFlyout is deprecated and may not be available in future releases. Instead, put - /// settings on their own page within the app. - /// - /// - /// - - _ElementUtilities._deprecated(strings.settingsFlyoutIsDeprecated); - - // Make sure there's an input element - this._element = element || _Global.document.createElement("div"); - this._id = this._element.id || _ElementUtilities._uniqueID(this._element); - this._writeProfilerMark("constructor,StartTM"); - - // Call the base overlay constructor helper - this._baseOverlayConstructor(this._element, options); - - this._addFirstDiv(); - this._addFinalDiv(); - - // Handle "esc" & "tab" key presses - this._element.addEventListener("keydown", this._handleKeyDown, true); - - // Start settings hidden - this._element.style.visibilty = "hidden"; - this._element.style.display = "none"; - - // Attach our css class - _ElementUtilities.addClass(this._element, _Constants.settingsFlyoutClass); - - var that = this; - this._dismissable = new _LightDismissService.LightDismissableElement({ - element: this._element, - tabIndex: this._element.hasAttribute("tabIndex") ? this._element.tabIndex : -1, - onLightDismiss: function () { - that.hide(); - }, - onTakeFocus: function (useSetActive) { - if (!that._dismissable.restoreFocus()) { - var firstDiv = that.element.querySelector("." + _Constants.firstDivClass); - if (firstDiv) { - if (!firstDiv.msSettingsFlyoutFocusOut) { - _ElementUtilities._addEventListener(firstDiv, "focusout", function () { settingsPageIsFocusedOnce = 1; }, false); - firstDiv.msSettingsFlyoutFocusOut = true; - } - - settingsPageIsFocusedOnce = 0; - _ElementUtilities._tryFocus(firstDiv, useSetActive); - } - } - }, - }); - - // apply the light theme styling to the win-content elements inside the SettingsFlyout - _ElementListUtilities.query("div.win-content", this._element). - forEach(function (e) { - if (!_ElementUtilities._matchesSelector(e, '.win-ui-dark, .win-ui-dark *')){ - _ElementUtilities.addClass(e, _Constants.flyoutLightClass); - } - }); - - // Make sure we have an ARIA role - var role = this._element.getAttribute("role"); - if (role === null || role === "" || role === undefined) { - this._element.setAttribute("role", "dialog"); - } - var label = this._element.getAttribute("aria-label"); - if (label === null || label === "" || label === undefined) { - this._element.setAttribute("aria-label", strings.ariaLabel); - } - - // Make sure animations are hooked up - this._currentAnimateIn = this._animateSlideIn; - this._currentAnimateOut = this._animateSlideOut; - this._writeProfilerMark("constructor,StopTM"); - }, { - // Public Properties - - /// - /// Width of the SettingsFlyout, "narrow", or "wide". - /// - /// SettingsFlyout.width may be altered or unavailable in future versions. Instead, style the CSS width property on elements with the .win-settingsflyout class. - /// - /// - /// - width: { - get: function () { - return this._width; - }, - - set: function (value) { - _ElementUtilities._deprecated(strings.widthDeprecationMessage); - if (value === this._width) { - return; - } - // Get rid of old class - if (this._width === settingsNarrow) { - _ElementUtilities.removeClass(this._element, _Constants.narrowClass); - } else if (this._width === settingsWide) { - _ElementUtilities.removeClass(this._element, _Constants.wideClass); - } - this._width = value; - - // Attach our new css class - if (this._width === settingsNarrow) { - _ElementUtilities.addClass(this._element, _Constants.narrowClass); - } else if (this._width === settingsWide) { - _ElementUtilities.addClass(this._element, _Constants.wideClass); - } - } - }, - - /// - /// Define the settings command Id for the SettingsFlyout control. - /// - /// - settingsCommandId: { - get: function () { - return this._settingsCommandId; - }, - - set: function (value) { - this._settingsCommandId = value; - } - }, - - /// Disable SettingsFlyout, setting or getting the HTML disabled attribute. When disabled the SettingsFlyout will no longer display with show(), and will hide if currently visible. - disabled: { - get: function () { - // Ensure it's a boolean because we're using the DOM element to keep in-sync - return !!this._element.disabled; - }, - set: function (value) { - // Force this check into a boolean because our current state could be a bit confused since we tie to the DOM element - value = !!value; - var oldValue = !!this._element.disabled; - if (oldValue !== value) { - this._element.disabled = value; - if (!this.hidden && this._element.disabled) { - this._dismiss(); - } - } - } - }, - - /// - /// Occurs immediately before the control is shown. - /// - onbeforeshow: createEvent(_Overlay._Overlay.beforeShow), - - /// - /// Occurs immediately after the control is shown. - /// - onaftershow: createEvent(_Overlay._Overlay.afterShow), - - /// - /// Occurs immediately before the control is hidden. - /// - onbeforehide: createEvent(_Overlay._Overlay.beforeHide), - - /// - /// Occurs immediately after the control is hidden. - /// - onafterhide: createEvent(_Overlay._Overlay.afterHide), - - show: function () { - /// - /// - /// Shows the SettingsFlyout, if hidden. - /// - /// - /// - // Just call private version to make appbar flags happy - - // Don't do anything if disabled - if (this.disabled) { - return; - } - this._writeProfilerMark("show,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndShow(). - this._show(); - }, - - _dispose: function SettingsFlyout_dispose() { - _LightDismissService.hidden(this._dismissable); - _Dispose.disposeSubTree(this.element); - this._dismiss(); - }, - - _show: function SettingsFlyout_show() { - // We call our base "_baseShow" because SettingsFlyout overrides show - if (this._baseShow()) { - // Verify that the firstDiv and finalDiv are in the correct location. - // Move them to the correct location or add them if they are not. - if (!_ElementUtilities.hasClass(this.element.children[0], _Constants.firstDivClass)) { - var firstDiv = this.element.querySelectorAll("." + _Constants.firstDivClass); - if (firstDiv && firstDiv.length > 0) { - firstDiv.item(0).parentNode.removeChild(firstDiv.item(0)); - } - - this._addFirstDiv(); - } - - if (!_ElementUtilities.hasClass(this.element.children[this.element.children.length - 1], _Constants.finalDivClass)) { - var finalDiv = this.element.querySelectorAll("." + _Constants.finalDivClass); - if (finalDiv && finalDiv.length > 0) { - finalDiv.item(0).parentNode.removeChild(finalDiv.item(0)); - } - - this._addFinalDiv(); - } - - this._setBackButtonsAriaLabel(); - - _LightDismissService.shown(this._dismissable); - } - }, - - _setBackButtonsAriaLabel: function SettingsFlyout_setBackButtonsAriaLabel() { - var backbuttons = this.element.querySelectorAll(".win-backbutton"); - var label; - for (var i = 0; i < backbuttons.length; i++) { - label = backbuttons[i].getAttribute("aria-label"); - if (label === null || label === "" || label === undefined) { - backbuttons[i].setAttribute("aria-label", strings.backbuttonAriaLabel); - } - } - }, - - hide: function () { - /// - /// - /// Hides the SettingsFlyout, if visible, regardless of other state. - /// - /// - /// - // Just call private version to make appbar flags happy - this._writeProfilerMark("hide,StartTM"); // The corresponding "stop" profiler mark is handled in _Overlay._baseEndHide(). - this._hide(); - }, - - _hide: function SettingsFlyout_hide() { - this._baseHide(); - }, - - _beforeEndHide: function SettingsFlyout_beforeEndHide() { - _LightDismissService.hidden(this._dismissable); - }, - - // SettingsFlyout animations - _animateSlideIn: function SettingsFlyout_animateSlideIn() { - var animateFromLeft = _shouldAnimateFromLeft(); - var offset = animateFromLeft ? "-100px" : "100px"; - _ElementListUtilities.query("div.win-content", this._element). - forEach(function (e) { Animations.enterPage(e, { left: offset }); }); - - var where, - width = this._element.offsetWidth; - // Slide in from right side or left side? - if (animateFromLeft) { - // RTL - where = { top: "0px", left: "-" + width + "px" }; - this._element.style.right = "auto"; - this._element.style.left = "0px"; - } else { - // From right side - where = { top: "0px", left: width + "px" }; - this._element.style.right = "0px"; - this._element.style.left = "auto"; - } - - this._element.style.opacity = 1; - this._element.style.visibility = "visible"; - - return Animations.showPanel(this._element, where); - }, - - _animateSlideOut: function SettingsFlyout_animateSlideOut() { - var where, - width = this._element.offsetWidth; - if (_shouldAnimateFromLeft()) { - // RTL - where = { top: "0px", left: width + "px" }; - this._element.style.right = "auto"; - this._element.style.left = "-" + width + "px"; - } else { - // From right side - where = { top: "0px", left: "-" + width + "px" }; - this._element.style.right = "-" + width + "px"; - this._element.style.left = "auto"; - } - - return Animations.showPanel(this._element, where); - }, - - _fragmentDiv: { - get: function SettingsFlyout_fragmentDiv_get() { - return this._fragDiv; - }, - - set: function SettingsFlyout_fragmentDiv_set(value) { - this._fragDiv = value; - } - }, - - _unloadPage: function SettingsFlyout_unloadPage(event) { - var settingsControl = event.currentTarget.winControl; - settingsControl.removeEventListener(_Overlay._Overlay.afterHide, this._unloadPage, false); - - Promise.as().then(function () { - if (settingsControl._fragmentDiv) { - _Global.document.body.removeChild(settingsControl._fragmentDiv); - settingsControl._fragmentDiv = null; - } - }); - }, - - _dismiss: function SettingsFlyout_dismiss() { - this.addEventListener(_Overlay._Overlay.afterHide, this._unloadPage, false); - this._hide(); - }, - - _handleKeyDown: function SettingsFlyout_handleKeyDown(event) { - if ((event.keyCode === Key.space || event.keyCode === Key.enter) - && (this.children[0] === _Global.document.activeElement)) { - event.preventDefault(); - event.stopPropagation(); - this.winControl._dismiss(); - } else if (event.shiftKey && event.keyCode === Key.tab - && this.children[0] === _Global.document.activeElement) { - event.preventDefault(); - event.stopPropagation(); - var _elms = this.getElementsByTagName("*"); - - for (var i = _elms.length - 2; i >= 0; i--) { - _elms[i].focus(); - - if (_elms[i] === _Global.document.activeElement) { - break; - } - } - } - }, - - _focusOnLastFocusableElementFromParent: function SettingsFlyout_focusOnLastFocusableElementFromParent() { - var active = _Global.document.activeElement; - if (!settingsPageIsFocusedOnce || !active || !_ElementUtilities.hasClass(active, _Constants.firstDivClass)) { - return; - } - - var _elms = this.parentElement.getElementsByTagName("*"); - - // There should be at least 1 element in addition to the firstDiv & finalDiv - if (_elms.length <= 2) { - return; - } - - // Get the tabIndex set to the finalDiv (which is the highest) - var _highestTabIndex = _elms[_elms.length - 1].tabIndex; - - // If there are positive tabIndices, set focus to the element with the highest tabIndex. - // Otherwise set focus to the last focusable element in DOM order. - var i; - if (_highestTabIndex) { - for (i = _elms.length - 2; i > 0; i--) { - if (_elms[i].tabIndex === _highestTabIndex) { - _elms[i].focus(); - break; - } - } - } else { - for (i = _elms.length - 2; i > 0; i--) { - // Skip
with undefined tabIndex (To work around Win8 bug #622245) - if ((_elms[i].tagName !== "DIV") || (_elms[i].getAttribute("tabIndex") !== null)) { - _elms[i].focus(); - - if (_elms[i] === _Global.document.activeElement) { - break; - } - } - } - } - }, - - _focusOnFirstFocusableElementFromParent: function SettingsFlyout_focusOnFirstFocusableElementFromParent() { - var active = _Global.document.activeElement; - if (!active || !_ElementUtilities.hasClass(active, _Constants.finalDivClass)) { - return; - } - var _elms = this.parentElement.getElementsByTagName("*"); - - // There should be at least 1 element in addition to the firstDiv & finalDiv - if (_elms.length <= 2) { - return; - } - - // Get the tabIndex set to the firstDiv (which is the lowest) - var _lowestTabIndex = _elms[0].tabIndex; - - // If there are positive tabIndices, set focus to the element with the lowest tabIndex. - // Otherwise set focus to the first focusable element in DOM order. - var i; - if (_lowestTabIndex) { - for (i = 1; i < _elms.length - 1; i++) { - if (_elms[i].tabIndex === _lowestTabIndex) { - _elms[i].focus(); - break; - } - } - } else { - for (i = 1; i < _elms.length - 1; i++) { - // Skip
with undefined tabIndex (To work around Win8 bug #622245) - if ((_elms[i].tagName !== "DIV") || (_elms[i].getAttribute("tabIndex") !== null)) { - _elms[i].focus(); - - if (_elms[i] === _Global.document.activeElement) { - break; - } - } - } - } - }, - - // Create and add a new first div to the beginning of the list - _addFirstDiv: function SettingsFlyout_addFirstDiv() { - var _elms = this._element.getElementsByTagName("*"); - var _minTab = 0; - for (var i = 0; i < _elms.length; i++) { - if ((0 < _elms[i].tabIndex) && (_minTab === 0 || _elms[i].tabIndex < _minTab)) { - _minTab = _elms[i].tabIndex; - } - } - var firstDiv = _Global.document.createElement("div"); - firstDiv.className = _Constants.firstDivClass; - firstDiv.style.display = "inline"; - firstDiv.setAttribute("role", "menuitem"); - firstDiv.setAttribute("aria-hidden", "true"); - firstDiv.tabIndex = _minTab; - _ElementUtilities._addEventListener(firstDiv, "focusin", this._focusOnLastFocusableElementFromParent, false); - - // add to beginning - if (this._element.children[0]) { - this._element.insertBefore(firstDiv, this._element.children[0]); - } else { - this._element.appendChild(firstDiv); - } - }, - - // Create and add a new final div to the end of the list - _addFinalDiv: function SettingsFlyout_addFinalDiv() { - var _elms = this._element.getElementsByTagName("*"); - var _maxTab = 0; - for (var i = 0; i < _elms.length; i++) { - if (_elms[i].tabIndex > _maxTab) { - _maxTab = _elms[i].tabIndex; - } - } - var finalDiv = _Global.document.createElement("div"); - finalDiv.className = _Constants.finalDivClass; - finalDiv.style.display = "inline"; - finalDiv.setAttribute("role", "menuitem"); - finalDiv.setAttribute("aria-hidden", "true"); - finalDiv.tabIndex = _maxTab; - _ElementUtilities._addEventListener(finalDiv, "focusin", this._focusOnFirstFocusableElementFromParent, false); - - this._element.appendChild(finalDiv); - }, - - _writeProfilerMark: function SettingsFlyout_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI.SettingsFlyout:" + this._id + ":" + text); - } - }); - - // Statics - SettingsFlyout.show = function () { - /// - /// - /// Shows the SettingsPane UI, if hidden, regardless of other states. - /// - /// - /// - /// Show the main settings pane - if (_WinRT.Windows.UI.ApplicationSettings.SettingsPane) { - _WinRT.Windows.UI.ApplicationSettings.SettingsPane.show(); - } - // And hide the WWA one - var elements = _Global.document.querySelectorAll('div[data-win-control="WinJS.UI.SettingsFlyout"]'); - var len = elements.length; - for (var i = 0; i < len; i++) { - var settingsFlyout = elements[i].winControl; - if (settingsFlyout) { - settingsFlyout._dismiss(); - } - } - }; - - var _settingsEvent = { event: undefined }; - SettingsFlyout.populateSettings = function (e) { - /// - /// - /// Loads a portion of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. - /// - /// - /// An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains - /// the applicationcommands sub-property that you set to an array of settings commands. - /// - /// - /// - _settingsEvent.event = e.detail; - - if (_settingsEvent.event.applicationcommands) { - var n = _WinRT.Windows.UI.ApplicationSettings; - Object.keys(_settingsEvent.event.applicationcommands).forEach(function (name) { - var setting = _settingsEvent.event.applicationcommands[name]; - if (!setting.title) { setting.title = name; } - var command = new n.SettingsCommand(name, setting.title, SettingsFlyout._onSettingsCommand); - _settingsEvent.event.e.request.applicationCommands.append(command); - }); - } - }; - - SettingsFlyout._onSettingsCommand = function (command) { - var id = command.id; - if (_settingsEvent.event.applicationcommands && _settingsEvent.event.applicationcommands[id]) { - SettingsFlyout.showSettings(id, _settingsEvent.event.applicationcommands[id].href); - } - }; - - SettingsFlyout.showSettings = function (id, path) { - /// - /// - /// Show the SettingsFlyout using the settings element identifier (ID) and the path of the page that contains the settings element. - /// - /// - /// The ID of the settings element. - /// - /// - /// The path of the page that contains the settings element. - /// - /// - /// - var control = _getChildSettingsControl(_Global.document, id); - if (control) { - control.show(); - } else if (path) { - var divElement = _Global.document.createElement("div"); - divElement = _Global.document.body.appendChild(divElement); - Pages.render(path, divElement).then(function () { - control = _getChildSettingsControl(divElement, id); - if (control) { - control._fragmentDiv = divElement; - control.show(); - } else { - _Global.document.body.removeChild(divElement); - } - }); - } else { - throw new _ErrorFromName("WinJS.UI.SettingsFlyout.BadReference", strings.badReference); - } - }; - - var strings = { - get ariaLabel() { return _Resources._getWinJSString("ui/settingsFlyoutAriaLabel").value; }, - get badReference() { return "Invalid argument: Invalid href to settings flyout fragment"; }, - get backbuttonAriaLabel() { return _Resources._getWinJSString("ui/backbuttonarialabel").value; }, - get widthDeprecationMessage() { return "SettingsFlyout.width may be altered or unavailable in future versions. Instead, style the CSS width property on elements with the .win-settingsflyout class."; }, - get settingsFlyoutIsDeprecated() { return "SettingsFlyout is deprecated and may not be available in future releases. Instead, put settings on their own page within the app."; } - }; - - return SettingsFlyout; - }) - }); - - -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/NavBar/_Command',[ - 'exports', - '../../Core/_Global', - '../../Core/_Base', - '../../Core/_ErrorFromName', - '../../Core/_Resources', - '../../ControlProcessor', - '../../Navigation', - '../../Utilities/_Control', - '../../Utilities/_ElementUtilities', - '../AppBar/_Icon' - ], function NavBarCommandInit(exports, _Global, _Base, _ErrorFromName, _Resources, ControlProcessor, Navigation, _Control, _ElementUtilities, _Icon) { - "use strict"; - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - _WinPressed: _Base.Namespace._lazy(function () { - var WinPressed = _Base.Class.define(function _WinPressed_ctor(element) { - // WinPressed is the combination of :hover:active - // :hover is delayed by trident for touch by 300ms so if you want :hover:active to work quickly you need to - // use this behavior. - // :active does not bubble to its parent like :hover does so this is also useful for that scenario. - this._element = element; - _ElementUtilities._addEventListener(this._element, "pointerdown", this._MSPointerDownButtonHandler.bind(this)); - }, { - _MSPointerDownButtonHandler: function _WinPressed_MSPointerDownButtonHandler(ev) { - if (!this._pointerUpBound) { - this._pointerUpBound = this._MSPointerUpHandler.bind(this); - this._pointerCancelBound = this._MSPointerCancelHandler.bind(this); - this._pointerOverBound = this._MSPointerOverHandler.bind(this); - this._pointerOutBound = this._MSPointerOutHandler.bind(this); - } - - if (ev.isPrimary) { - if (this._pointerId) { - this._resetPointer(); - } - - if (!_ElementUtilities._matchesSelector(ev.target, ".win-interactive, .win-interactive *")) { - this._pointerId = ev.pointerId; - - _ElementUtilities._addEventListener(_Global, "pointerup", this._pointerUpBound, true); - _ElementUtilities._addEventListener(_Global, "pointercancel", this._pointerCancelBound), true; - _ElementUtilities._addEventListener(this._element, "pointerover", this._pointerOverBound, true); - _ElementUtilities._addEventListener(this._element, "pointerout", this._pointerOutBound, true); - - _ElementUtilities.addClass(this._element, WinPressed.winPressed); - } - } - }, - - _MSPointerOverHandler: function _WinPressed_MSPointerOverHandler(ev) { - if (this._pointerId === ev.pointerId) { - _ElementUtilities.addClass(this._element, WinPressed.winPressed); - } - }, - - _MSPointerOutHandler: function _WinPressed_MSPointerOutHandler(ev) { - if (this._pointerId === ev.pointerId) { - _ElementUtilities.removeClass(this._element, WinPressed.winPressed); - } - }, - - _MSPointerCancelHandler: function _WinPressed_MSPointerCancelHandler(ev) { - if (this._pointerId === ev.pointerId) { - this._resetPointer(); - } - }, - - _MSPointerUpHandler: function _WinPressed_MSPointerUpHandler(ev) { - if (this._pointerId === ev.pointerId) { - this._resetPointer(); - } - }, - - _resetPointer: function _WinPressed_resetPointer() { - this._pointerId = null; - - _ElementUtilities._removeEventListener(_Global, "pointerup", this._pointerUpBound, true); - _ElementUtilities._removeEventListener(_Global, "pointercancel", this._pointerCancelBound, true); - _ElementUtilities._removeEventListener(this._element, "pointerover", this._pointerOverBound, true); - _ElementUtilities._removeEventListener(this._element, "pointerout", this._pointerOutBound, true); - - _ElementUtilities.removeClass(this._element, WinPressed.winPressed); - }, - - dispose: function _WinPressed_dispose() { - if (this._disposed) { - return; - } - this._disposed = true; - - this._resetPointer(); - } - }, { - winPressed: "win-pressed" - }); - - return WinPressed; - }), - /// - /// - /// Represents a navigation command in an NavBarContainer. - /// - /// - /// - /// - /// - ///
]]> - /// Styles the entire NavBarCommand control. - /// Styles the main button in a NavBarCommand. - /// Styles the split button in a NavBarCommand - /// Styles the icon in the main button of a NavBarCommand. - /// Styles the label in the main button of a NavBarCommand. - /// - /// - NavBarCommand: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - var strings = { - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; } - }; - - var NavBarCommand = _Base.Class.define(function NavBarCommand_ctor(element, options) { - /// - /// - /// Creates a new NavBarCommand. - /// - /// - /// The DOM element that will host the new NavBarCommand control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". - /// - /// - /// The new NavBarCommand. - /// - /// - /// - element = element || _Global.document.createElement("DIV"); - options = options || {}; - - if (element.winControl) { - throw new _ErrorFromName("WinJS.UI.NavBarCommand.DuplicateConstruction", strings.duplicateConstruction); - } - - // Attaching JS control to DOM element - element.winControl = this; - this._element = element; - _ElementUtilities.addClass(this.element, NavBarCommand._ClassName.navbarcommand); - _ElementUtilities.addClass(this.element, "win-disposable"); - - this._tooltip = null; - this._splitOpened = false; - this._buildDom(); - element.addEventListener('keydown', this._keydownHandler.bind(this)); - - _Control.setOptions(this, options); - }, { - /// - element: { - get: function () { - return this._element; - } - }, - - /// - /// Gets or sets the label of the NavBarCommand. - /// - /// - label: { - get: function () { - return this._label; - }, - set: function (value) { - this._label = value; - this._labelEl.textContent = value; - } - }, - - /// - /// Gets or sets the tooltip of the NavBarCommand. - /// - /// - tooltip: { - get: function () { - return this._tooltip; - }, - set: function (value) { - this._tooltip = value; - if (this._tooltip || this._tooltip === "") { - this._element.setAttribute('title', this._tooltip); - } else { - this._element.removeAttribute('title'); - } - } - }, - - /// - /// Gets or sets the icon of the NavBarCommand. This value is either one of the values of the AppBarIcon enumeration or the path of a custom PNG file. - /// - /// - icon: { - get: function () { - return this._icon; - }, - set: function (value) { - this._icon = (_Icon[value] || value); - - // If the icon's a single character, presume a glyph - if (this._icon && this._icon.length === 1) { - // Set the glyph - this._imageSpan.textContent = this._icon; - this._imageSpan.style.backgroundImage = ""; - this._imageSpan.style.msHighContrastAdjust = ""; - this._imageSpan.style.display = ""; - } else if (this._icon && this._icon.length > 1) { - // Must be an image, set that - this._imageSpan.textContent = ""; - this._imageSpan.style.backgroundImage = this._icon; - this._imageSpan.style.msHighContrastAdjust = "none"; - this._imageSpan.style.display = ""; - } else { - this._imageSpan.textContent = ""; - this._imageSpan.style.backgroundImage = ""; - this._imageSpan.style.msHighContrastAdjust = ""; - this._imageSpan.style.display = "none"; - } - } - }, - - /// - /// Gets or sets the command's target location. - /// - /// - location: { - get: function () { - return this._location; - }, - set: function (value) { - this._location = value; - } - }, - - /// - /// Gets or sets the state value used for navigation. The command passes this object to the WinJS.Navigation.navigate function. - /// - /// - state: { - get: function () { - return this._state; - }, - set: function (value) { - this._state = value; - } - }, - - /// - /// Gets or sets a value that specifies whether the NavBarCommand has a split button. - /// - /// - splitButton: { - get: function () { - return this._split; - }, - set: function (value) { - this._split = value; - if (this._split) { - this._splitButtonEl.style.display = ""; - } else { - this._splitButtonEl.style.display = "none"; - } - } - }, - - /// - splitOpened: { - get: function () { - return this._splitOpened; - }, - set: function (value) { - if (this._splitOpened !== !!value) { - this._toggleSplit(); - } - } - }, - - _toggleSplit: function NavBarCommand_toggleSplit() { - this._splitOpened = !this._splitOpened; - if (this._splitOpened) { - _ElementUtilities.addClass(this._splitButtonEl, NavBarCommand._ClassName.navbarcommandsplitbuttonopened); - this._splitButtonEl.setAttribute("aria-expanded", "true"); - } else { - _ElementUtilities.removeClass(this._splitButtonEl, NavBarCommand._ClassName.navbarcommandsplitbuttonopened); - this._splitButtonEl.setAttribute("aria-expanded", "false"); - } - this._fireEvent(NavBarCommand._EventName._splitToggle); - }, - - _rtl: { - get: function () { - return _Global.getComputedStyle(this.element).direction === "rtl"; - } - }, - - _keydownHandler: function NavBarCommand_keydownHandler(ev) { - if (_ElementUtilities._matchesSelector(ev.target, ".win-interactive, .win-interactive *")) { - return; - } - - var leftStr = this._rtl ? Key.rightArrow : Key.leftArrow; - var rightStr = this._rtl ? Key.leftArrow : Key.rightArrow; - - if (!ev.altKey && (ev.keyCode === leftStr || ev.keyCode === Key.home || ev.keyCode === Key.end) && ev.target === this._splitButtonEl) { - _ElementUtilities._setActive(this._buttonEl); - if (ev.keyCode === leftStr) { - ev.stopPropagation(); - } - ev.preventDefault(); - } else if (!ev.altKey && ev.keyCode === rightStr && this.splitButton && (ev.target === this._buttonEl || this._buttonEl.contains(ev.target))) { - _ElementUtilities._setActive(this._splitButtonEl); - if (ev.keyCode === rightStr) { - ev.stopPropagation(); - } - ev.preventDefault(); - } else if ((ev.keyCode === Key.space || ev.keyCode === Key.enter) && (ev.target === this._buttonEl || this._buttonEl.contains(ev.target))) { - if (this.location) { - Navigation.navigate(this.location, this.state); - } - this._fireEvent(NavBarCommand._EventName._invoked); - } else if ((ev.keyCode === Key.space || ev.keyCode === Key.enter) && ev.target === this._splitButtonEl) { - this._toggleSplit(); - } - }, - - _getFocusInto: function NavBarCommand_getFocusInto(keyCode) { - var leftStr = this._rtl ? Key.rightArrow : Key.leftArrow; - if ((keyCode === leftStr) && this.splitButton) { - return this._splitButtonEl; - } else { - return this._buttonEl; - } - }, - - _buildDom: function NavBarCommand_buildDom() { - var markup = - '' + - ''; - this.element.insertAdjacentHTML("afterBegin", markup); - - this._buttonEl = this.element.firstElementChild; - this._buttonPressedBehavior = new exports._WinPressed(this._buttonEl); - this._contentEl = this._buttonEl.firstElementChild; - this._imageSpan = this._contentEl.firstElementChild; - this._imageSpan.style.display = "none"; - this._labelEl = this._imageSpan.nextElementSibling; - this._splitButtonEl = this._buttonEl.nextElementSibling; - this._splitButtonPressedBehavior = new exports._WinPressed(this._splitButtonEl); - this._splitButtonEl.style.display = "none"; - - _ElementUtilities._ensureId(this._buttonEl); - this._splitButtonEl.setAttribute("aria-labelledby", this._buttonEl.id); - - this._buttonEl.addEventListener("click", this._handleButtonClick.bind(this)); - - var mutationObserver = new _ElementUtilities._MutationObserver(this._splitButtonAriaExpandedPropertyChangeHandler.bind(this)); - mutationObserver.observe(this._splitButtonEl, { attributes: true, attributeFilter: ["aria-expanded"] }); - this._splitButtonEl.addEventListener("click", this._handleSplitButtonClick.bind(this)); - - // reparent any other elements. - var tempEl = this._splitButtonEl.nextSibling; - while (tempEl) { - this._buttonEl.insertBefore(tempEl, this._contentEl); - if (tempEl.nodeName !== "#text") { - ControlProcessor.processAll(tempEl); - } - tempEl = this._splitButtonEl.nextSibling; - } - }, - - _handleButtonClick: function NavBarCommand_handleButtonClick(ev) { - var srcElement = ev.target; - if (!_ElementUtilities._matchesSelector(srcElement, ".win-interactive, .win-interactive *")) { - if (this.location) { - Navigation.navigate(this.location, this.state); - } - this._fireEvent(NavBarCommand._EventName._invoked); - } - }, - - _splitButtonAriaExpandedPropertyChangeHandler: function NavBarCommand_splitButtonAriaExpandedPropertyChangeHandler() { - if ((this._splitButtonEl.getAttribute("aria-expanded") === "true") !== this._splitOpened) { - this._toggleSplit(); - } - }, - - _handleSplitButtonClick: function NavBarCommand_handleSplitButtonClick() { - this._toggleSplit(); - }, - - _fireEvent: function NavBarCommand_fireEvent(type, detail) { - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(type, true, false, detail); - this.element.dispatchEvent(event); - }, - - dispose: function NavBarCommand_dispose() { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - - this._buttonPressedBehavior.dispose(); - this._splitButtonPressedBehavior.dispose(); - } - }, { - _ClassName: { - navbarcommand: "win-navbarcommand", - navbarcommandbutton: "win-navbarcommand-button", - navbarcommandbuttoncontent: "win-navbarcommand-button-content", - navbarcommandsplitbutton: "win-navbarcommand-splitbutton", - navbarcommandsplitbuttonopened: "win-navbarcommand-splitbutton-opened", - navbarcommandicon: "win-navbarcommand-icon", - navbarcommandlabel: "win-navbarcommand-label" - }, - _EventName: { - _invoked: "_invoked", - _splitToggle: "_splittoggle" - } - }); - _Base.Class.mix(NavBarCommand, _Control.DOMEventMixin); - return NavBarCommand; - }) - }); - -}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/NavBar/_Container',[ - 'exports', - '../../Core/_Global', - '../../Core/_Base', - '../../Core/_BaseUtils', - '../../Core/_ErrorFromName', - '../../Core/_Events', - '../../Core/_Log', - '../../Core/_Resources', - '../../Core/_WriteProfilerMark', - '../../Animations', - '../../Animations/_TransitionAnimation', - '../../BindingList', - '../../ControlProcessor', - '../../Navigation', - '../../Promise', - '../../Scheduler', - '../../Utilities/_Control', - '../../Utilities/_ElementUtilities', - '../../Utilities/_KeyboardBehavior', - '../../Utilities/_UI', - '../_LegacyAppBar/_Constants', - '../Repeater', - './_Command' -], function NavBarContainerInit(exports, _Global, _Base, _BaseUtils, _ErrorFromName, _Events, _Log, _Resources, _WriteProfilerMark, Animations, _TransitionAnimation, BindingList, ControlProcessor, Navigation, Promise, Scheduler, _Control, _ElementUtilities, _KeyboardBehavior, _UI, _Constants, Repeater, _Command) { - "use strict"; - - function nobodyHasFocus() { - return _Global.document.activeElement === null || _Global.document.activeElement === _Global.document.body; - } - - _Base.Namespace._moduleDefine(exports, "WinJS.UI", { - /// - /// - /// Contains a group of NavBarCommand objects in a NavBar. - /// - /// - /// - /// - /// - /// - ///
- ///
]]> - /// Raised when a NavBarCommand is invoked. - /// Raised when the split button on a NavBarCommand is toggled. - /// Styles the entire NavBarContainer control. - /// - /// Styles the page indication for the NavBarContainer. - /// - /// Styles the page indication for each page. - /// - /// Styles the indication of the current page. - /// - /// Styles the area that contains items for the NavBarContainer. - /// Styles left and right navigation arrows. - /// Styles the left navigation arrow. - /// Styles the right navigation arrow. - /// - /// - NavBarContainer: _Base.Namespace._lazy(function () { - var Key = _ElementUtilities.Key; - - var buttonFadeDelay = 3000; - var PT_TOUCH = _ElementUtilities._MSPointerEvent.MSPOINTER_TYPE_TOUCH || "touch"; - var MS_MANIPULATION_STATE_STOPPED = 0; - - var createEvent = _Events._createEventProperty; - var eventNames = { - invoked: "invoked", - splittoggle: "splittoggle" - }; - - var strings = { - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get navBarContainerViewportAriaLabel() { return _Resources._getWinJSString("ui/navBarContainerViewportAriaLabel").value; } - }; - - var NavBarContainer = _Base.Class.define(function NavBarContainer_ctor(element, options) { - /// - /// - /// Creates a new NavBarContainer. - /// - /// - /// The DOM element that will host the NavBarContainer control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". - /// - /// - /// The new NavBarContainer. - /// - /// - /// - - element = element || _Global.document.createElement("DIV"); - this._id = element.id || _ElementUtilities._uniqueID(element); - this._writeProfilerMark("constructor,StartTM"); - - options = options || {}; - - if (element.winControl) { - throw new _ErrorFromName("WinJS.UI.NavBarContainer.DuplicateConstruction", strings.duplicateConstruction); - } - - // Attaching JS control to DOM element - element.winControl = this; - this._element = element; - _ElementUtilities.addClass(this.element, NavBarContainer._ClassName.navbarcontainer); - _ElementUtilities.addClass(this.element, "win-disposable"); - if (!element.getAttribute("tabIndex")) { - element.tabIndex = -1; - } - - this._focusCurrentItemPassivelyBound = this._focusCurrentItemPassively.bind(this); - this._closeSplitAndResetBound = this._closeSplitAndReset.bind(this); - this._currentManipulationState = MS_MANIPULATION_STATE_STOPPED; - - this._panningDisabled = !_ElementUtilities._supportsSnapPoints; - this._fixedSize = false; - this._maxRows = 1; - this._sizes = {}; - - this._setupTree(); - - this._duringConstructor = true; - - this._dataChangingBound = this._dataChanging.bind(this); - this._dataChangedBound = this._dataChanged.bind(this); - - Navigation.addEventListener('navigated', this._closeSplitAndResetBound); - - // Don't use set options for the properties so we can control the ordering to avoid rendering multiple times. - this.layout = options.layout || _UI.Orientation.horizontal; - if (options.maxRows) { - this.maxRows = options.maxRows; - } - if (options.template) { - this.template = options.template; - } - if (options.data) { - this.data = options.data; - } - if (options.fixedSize) { - this.fixedSize = options.fixedSize; - } - - // Events only - _Control._setOptions(this, options, true); - - this._duringConstructor = false; - - if (options.currentIndex) { - this.currentIndex = options.currentIndex; - } - - this._updatePageUI(); - - Scheduler.schedule(function NavBarContainer_async_initialize() { - this._updateAppBarReference(); - }, Scheduler.Priority.normal, this, "WinJS.UI.NavBarContainer_async_initialize"); - - this._writeProfilerMark("constructor,StopTM"); - }, { - /// - element: { - get: function () { - return this._element; - } - }, - - /// - /// Gets or sets a Template or custom rendering function that defines the HTML of each item within the NavBarContainer. - /// - /// - template: { - get: function () { - return this._template; - }, - set: function (value) { - this._template = value; - if (this._repeater) { - var hadFocus = this.element.contains(_Global.document.activeElement); - - if (!this._duringConstructor) { - this._closeSplitIfOpen(); - } - - // the repeater's template is wired up to this._render() so just resetting it will rebuild the tree. - this._repeater.template = this._repeater.template; - - if (!this._duringConstructor) { - this._measured = false; - this._sizes.itemMeasured = false; - this._reset(); - if (hadFocus) { - this._keyboardBehavior._focus(0); - } - } - } - } - }, - - _render: function NavBarContainer_render(item) { - var navbarCommandEl = _Global.document.createElement('div'); - - var template = this._template; - if (template) { - if (template.render) { - template.render(item, navbarCommandEl); - } else if (template.winControl && template.winControl.render) { - template.winControl.render(item, navbarCommandEl); - } else { - navbarCommandEl.appendChild(template(item)); - } - } - - // Create the NavBarCommand after calling render so that the reparenting in navbarCommand works. - var navbarCommand = new _Command.NavBarCommand(navbarCommandEl, item); - return navbarCommand._element; - }, - - /// - /// Gets or sets the WinJS.Binding.List that provides the NavBarContainer with items to display. - /// - /// - data: { - get: function () { - return this._repeater && this._repeater.data; - }, - set: function (value) { - if (!value) { - value = new BindingList.List(); - } - - if (!this._duringConstructor) { - this._closeSplitIfOpen(); - } - - this._removeDataChangingEvents(); - this._removeDataChangedEvents(); - - var hadFocus = this.element.contains(_Global.document.activeElement); - - if (!this._repeater) { - this._surfaceEl.innerHTML = ""; - this._repeater = new Repeater.Repeater(this._surfaceEl, { - template: this._render.bind(this) - }); - } - - this._addDataChangingEvents(value); - this._repeater.data = value; - this._addDataChangedEvents(value); - - if (!this._duringConstructor) { - this._measured = false; - this._sizes.itemMeasured = false; - this._reset(); - if (hadFocus) { - this._keyboardBehavior._focus(0); - } - } - } - }, - - /// - /// Gets or sets the number of rows allowed to be used before items are placed on additional pages. - /// - /// - maxRows: { - get: function () { - return this._maxRows; - }, - set: function (value) { - value = (+value === value) ? value : 1; - this._maxRows = Math.max(1, value); - - if (!this._duringConstructor) { - this._closeSplitIfOpen(); - - this._measured = false; - this._reset(); - } - } - }, - - /// - /// Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. The default is "horizontal". - /// - /// - layout: { - get: function () { - return this._layout; - }, - set: function (value) { - if (value === _UI.Orientation.vertical) { - this._layout = _UI.Orientation.vertical; - _ElementUtilities.removeClass(this.element, NavBarContainer._ClassName.horizontal); - _ElementUtilities.addClass(this.element, NavBarContainer._ClassName.vertical); - } else { - this._layout = _UI.Orientation.horizontal; - _ElementUtilities.removeClass(this.element, NavBarContainer._ClassName.vertical); - _ElementUtilities.addClass(this.element, NavBarContainer._ClassName.horizontal); - } - - this._viewportEl.style.msScrollSnapType = ""; - this._zooming = false; - - if (!this._duringConstructor) { - this._measured = false; - this._sizes.itemMeasured = false; - this._ensureVisible(this._keyboardBehavior.currentIndex, true); - this._updatePageUI(); - this._closeSplitIfOpen(); - } - } - }, - - /// - currentIndex: { - get: function () { - return this._keyboardBehavior.currentIndex; - }, - set: function (value) { - if (value === +value) { - var hadFocus = this.element.contains(_Global.document.activeElement); - - this._keyboardBehavior.currentIndex = value; - - this._ensureVisible(this._keyboardBehavior.currentIndex, true); - - if (hadFocus) { - this._keyboardBehavior._focus(); - } - } - } - }, - - /// - /// Gets or sets a value that specifies whether child NavBarCommand objects should be a fixed width when there are multiple pages. A value of true indicates - /// that the NavBarCommand objects use a fixed width; a value of false indicates that they use a dynamic width. - /// - /// - fixedSize: { - get: function () { - return this._fixedSize; - }, - set: function (value) { - this._fixedSize = !!value; - - if (!this._duringConstructor) { - this._closeSplitIfOpen(); - - if (!this._measured) { - this._measure(); - } else if (this._surfaceEl.children.length > 0) { - this._updateGridStyles(); - } - } - } - }, - - /// - /// Raised when a NavBarCommand has been invoked. - /// - /// - oninvoked: createEvent(eventNames.invoked), - - /// - /// Raised when the split button on a NavBarCommand is toggled. - /// - /// - onsplittoggle: createEvent(eventNames.splittoggle), - - forceLayout: function NavBarContainer_forceLayout() { - /// - /// - /// Forces the NavBarContainer to update scroll positions and if the NavBar has changed size, it will also re-measure. - /// Use this function when making the NavBarContainer visible again after you set its style.display property to "none". - /// - /// - /// - this._resizeHandler(); - if (this._measured) { - this._scrollPosition = _ElementUtilities.getScrollPosition(this._viewportEl)[(this.layout === _UI.Orientation.horizontal ? "scrollLeft" : "scrollTop")]; - } - - this._duringForceLayout = true; - this._ensureVisible(this._keyboardBehavior.currentIndex, true); - this._updatePageUI(); - this._duringForceLayout = false; - }, - - _updateAppBarReference: function NavBarContainer_updateAppBarReference() { - if (!this._appBarEl || !this._appBarEl.contains(this.element)) { - if (this._appBarEl) { - this._appBarEl.removeEventListener('beforeopen', this._closeSplitAndResetBound); - this._appBarEl.removeEventListener('beforeopen', this._resizeImplBound); - this._appBarEl.removeEventListener('afteropen', this._focusCurrentItemPassivelyBound); - } - - var appBarEl = this.element.parentNode; - while (appBarEl && !_ElementUtilities.hasClass(appBarEl, _Constants.appBarClass)) { - appBarEl = appBarEl.parentNode; - } - this._appBarEl = appBarEl; - - if (this._appBarEl) { - this._appBarEl.addEventListener('beforeopen', this._closeSplitAndResetBound); - this._appBarEl.addEventListener('afteropen', this._focusCurrentItemPassivelyBound); - } - } - }, - - _closeSplitAndReset: function NavBarContainer_closeSplitAndReset() { - this._closeSplitIfOpen(); - this._reset(); - }, - - _dataChanging: function NavBarContainer_dataChanging(ev) { - // Store the element that was active so that we can detect - // if the focus went away because of the data change. - this._elementHadFocus = _Global.document.activeElement; - - if (this._currentSplitNavItem && this._currentSplitNavItem.splitOpened) { - if (ev.type === "itemremoved") { - if (this._surfaceEl.children[ev.detail.index].winControl === this._currentSplitNavItem) { - this._closeSplitIfOpen(); - } - } else if (ev.type === "itemchanged") { - if (this._surfaceEl.children[ev.detail.index].winControl === this._currentSplitNavItem) { - this._closeSplitIfOpen(); - } - } else if (ev.type === "itemmoved") { - if (this._surfaceEl.children[ev.detail.oldIndex].winControl === this._currentSplitNavItem) { - this._closeSplitIfOpen(); - } - } else if (ev.type === "reload") { - this._closeSplitIfOpen(); - } - } - }, - - _dataChanged: function NavBarContainer_dataChanged(ev) { - this._measured = false; - - if (ev.type === "itemremoved") { - if (ev.detail.index < this._keyboardBehavior.currentIndex) { - this._keyboardBehavior.currentIndex--; - } else if (ev.detail.index === this._keyboardBehavior.currentIndex) { - // This clamps if the item being removed was the last item in the list - this._keyboardBehavior.currentIndex = this._keyboardBehavior.currentIndex; - if (nobodyHasFocus() && this._elementHadFocus) { - this._keyboardBehavior._focus(); - } - } - } else if (ev.type === "itemchanged") { - if (ev.detail.index === this._keyboardBehavior.currentIndex) { - if (nobodyHasFocus() && this._elementHadFocus) { - this._keyboardBehavior._focus(); - } - } - } else if (ev.type === "iteminserted") { - if (ev.detail.index <= this._keyboardBehavior.currentIndex) { - this._keyboardBehavior.currentIndex++; - } - } else if (ev.type === "itemmoved") { - if (ev.detail.oldIndex === this._keyboardBehavior.currentIndex) { - this._keyboardBehavior.currentIndex = ev.detail.newIndex; - if (nobodyHasFocus() && this._elementHadFocus) { - this._keyboardBehavior._focus(); - } - } - } else if (ev.type === "reload") { - this._keyboardBehavior.currentIndex = 0; - if (nobodyHasFocus() && this._elementHadFocus) { - this._keyboardBehavior._focus(); - } - } - - this._ensureVisible(this._keyboardBehavior.currentIndex, true); - this._updatePageUI(); - }, - - _focusCurrentItemPassively: function NavBarContainer_focusCurrentItemPassively() { - if (this.element.contains(_Global.document.activeElement)) { - this._keyboardBehavior._focus(); - } - }, - - _reset: function NavBarContainer_reset() { - this._keyboardBehavior.currentIndex = 0; - - if (this.element.contains(_Global.document.activeElement)) { - this._keyboardBehavior._focus(0); - } - - this._viewportEl.style.msScrollSnapType = ""; - this._zooming = false; - - this._ensureVisible(0, true); - this._updatePageUI(); - }, - - _removeDataChangedEvents: function NavBarContainer_removeDataChangedEvents() { - if (this._repeater) { - this._repeater.data.removeEventListener("itemchanged", this._dataChangedBound); - this._repeater.data.removeEventListener("iteminserted", this._dataChangedBound); - this._repeater.data.removeEventListener("itemmoved", this._dataChangedBound); - this._repeater.data.removeEventListener("itemremoved", this._dataChangedBound); - this._repeater.data.removeEventListener("reload", this._dataChangedBound); - } - }, - - _addDataChangedEvents: function NavBarContainer_addDataChangedEvents() { - if (this._repeater) { - this._repeater.data.addEventListener("itemchanged", this._dataChangedBound); - this._repeater.data.addEventListener("iteminserted", this._dataChangedBound); - this._repeater.data.addEventListener("itemmoved", this._dataChangedBound); - this._repeater.data.addEventListener("itemremoved", this._dataChangedBound); - this._repeater.data.addEventListener("reload", this._dataChangedBound); - } - }, - - _removeDataChangingEvents: function NavBarContainer_removeDataChangingEvents() { - if (this._repeater) { - this._repeater.data.removeEventListener("itemchanged", this._dataChangingBound); - this._repeater.data.removeEventListener("iteminserted", this._dataChangingBound); - this._repeater.data.removeEventListener("itemmoved", this._dataChangingBound); - this._repeater.data.removeEventListener("itemremoved", this._dataChangingBound); - this._repeater.data.removeEventListener("reload", this._dataChangingBound); - } - }, - - _addDataChangingEvents: function NavBarContainer_addDataChangingEvents(bindingList) { - bindingList.addEventListener("itemchanged", this._dataChangingBound); - bindingList.addEventListener("iteminserted", this._dataChangingBound); - bindingList.addEventListener("itemmoved", this._dataChangingBound); - bindingList.addEventListener("itemremoved", this._dataChangingBound); - bindingList.addEventListener("reload", this._dataChangingBound); - }, - - _mouseleave: function NavBarContainer_mouseleave() { - if (this._mouseInViewport) { - this._mouseInViewport = false; - this._updateArrows(); - } - }, - - _MSPointerDown: function NavBarContainer_MSPointerDown(ev) { - if (ev.pointerType === PT_TOUCH) { - if (this._mouseInViewport) { - this._mouseInViewport = false; - this._updateArrows(); - } - } - }, - - _MSPointerMove: function NavBarContainer_MSPointerMove(ev) { - if (ev.pointerType !== PT_TOUCH) { - if (!this._mouseInViewport) { - this._mouseInViewport = true; - this._updateArrows(); - } - } - }, - - _setupTree: function NavBarContainer_setupTree() { - this._animateNextPreviousButtons = Promise.wrap(); - this._element.addEventListener('mouseleave', this._mouseleave.bind(this)); - _ElementUtilities._addEventListener(this._element, 'pointerdown', this._MSPointerDown.bind(this)); - _ElementUtilities._addEventListener(this._element, 'pointermove', this._MSPointerMove.bind(this)); - _ElementUtilities._addEventListener(this._element, "focusin", this._focusHandler.bind(this), false); - - this._pageindicatorsEl = _Global.document.createElement('div'); - _ElementUtilities.addClass(this._pageindicatorsEl, NavBarContainer._ClassName.pageindicators); - this._element.appendChild(this._pageindicatorsEl); - - this._ariaStartMarker = _Global.document.createElement("div"); - this._element.appendChild(this._ariaStartMarker); - - this._viewportEl = _Global.document.createElement('div'); - _ElementUtilities.addClass(this._viewportEl, NavBarContainer._ClassName.viewport); - this._element.appendChild(this._viewportEl); - this._viewportEl.setAttribute("role", "group"); - this._viewportEl.setAttribute("aria-label", strings.navBarContainerViewportAriaLabel); - - this._boundResizeHandler = this._resizeHandler.bind(this); - _ElementUtilities._resizeNotifier.subscribe(this._element, this._boundResizeHandler); - this._viewportEl.addEventListener("mselementresize", this._resizeHandler.bind(this)); - this._viewportEl.addEventListener("scroll", this._scrollHandler.bind(this)); - this._viewportEl.addEventListener("MSManipulationStateChanged", this._MSManipulationStateChangedHandler.bind(this)); - - this._ariaEndMarker = _Global.document.createElement("div"); - this._element.appendChild(this._ariaEndMarker); - - this._surfaceEl = _Global.document.createElement('div'); - _ElementUtilities.addClass(this._surfaceEl, NavBarContainer._ClassName.surface); - this._viewportEl.appendChild(this._surfaceEl); - - this._surfaceEl.addEventListener("_invoked", this._navbarCommandInvokedHandler.bind(this)); - this._surfaceEl.addEventListener("_splittoggle", this._navbarCommandSplitToggleHandler.bind(this)); - _ElementUtilities._addEventListener(this._surfaceEl, "focusin", this._itemsFocusHandler.bind(this), false); - this._surfaceEl.addEventListener("keydown", this._keyDownHandler.bind(this)); - - // Reparent NavBarCommands which were in declarative markup - var tempEl = this.element.firstElementChild; - while (tempEl !== this._pageindicatorsEl) { - this._surfaceEl.appendChild(tempEl); - ControlProcessor.process(tempEl); - tempEl = this.element.firstElementChild; - } - - this._leftArrowEl = _Global.document.createElement('div'); - _ElementUtilities.addClass(this._leftArrowEl, NavBarContainer._ClassName.navleftarrow); - _ElementUtilities.addClass(this._leftArrowEl, NavBarContainer._ClassName.navarrow); - this._element.appendChild(this._leftArrowEl); - this._leftArrowEl.addEventListener('click', this._goLeft.bind(this)); - this._leftArrowEl.style.opacity = 0; - this._leftArrowEl.style.visibility = 'hidden'; - this._leftArrowFadeOut = Promise.wrap(); - - this._rightArrowEl = _Global.document.createElement('div'); - _ElementUtilities.addClass(this._rightArrowEl, NavBarContainer._ClassName.navrightarrow); - _ElementUtilities.addClass(this._rightArrowEl, NavBarContainer._ClassName.navarrow); - this._element.appendChild(this._rightArrowEl); - this._rightArrowEl.addEventListener('click', this._goRight.bind(this)); - this._rightArrowEl.style.opacity = 0; - this._rightArrowEl.style.visibility = 'hidden'; - this._rightArrowFadeOut = Promise.wrap(); - - this._keyboardBehavior = new _KeyboardBehavior._KeyboardBehavior(this._surfaceEl, { - scroller: this._viewportEl - }); - this._winKeyboard = new _KeyboardBehavior._WinKeyboard(this._surfaceEl); - }, - - _goRight: function NavBarContainer_goRight() { - if (this._sizes.rtl) { - this._goPrev(); - } else { - this._goNext(); - } - }, - - _goLeft: function NavBarContainer_goLeft() { - if (this._sizes.rtl) { - this._goNext(); - } else { - this._goPrev(); - } - }, - - _goNext: function NavBarContainer_goNext() { - this._measure(); - var itemsPerPage = this._sizes.rowsPerPage * this._sizes.columnsPerPage; - var targetPage = Math.min(Math.floor(this._keyboardBehavior.currentIndex / itemsPerPage) + 1, this._sizes.pages - 1); - this._keyboardBehavior.currentIndex = Math.min(itemsPerPage * targetPage, this._surfaceEl.children.length); - this._keyboardBehavior._focus(); - }, - - _goPrev: function NavBarContainer_goPrev() { - this._measure(); - var itemsPerPage = this._sizes.rowsPerPage * this._sizes.columnsPerPage; - var targetPage = Math.max(0, Math.floor(this._keyboardBehavior.currentIndex / itemsPerPage) - 1); - this._keyboardBehavior.currentIndex = Math.max(itemsPerPage * targetPage, 0); - this._keyboardBehavior._focus(); - }, - - _currentPage: { - get: function () { - if (this.layout === _UI.Orientation.horizontal) { - this._measure(); - if (this._sizes.viewportOffsetWidth > 0) { - return Math.min(this._sizes.pages - 1, Math.round(this._scrollPosition / this._sizes.viewportOffsetWidth)); - } - } - return 0; - } - }, - - _resizeHandler: function NavBarContainer_resizeHandler() { - if (this._disposed) { return; } - if (!this._measured) { return; } - var viewportResized = this.layout === _UI.Orientation.horizontal - ? this._sizes.viewportOffsetWidth !== parseFloat(_Global.getComputedStyle(this._viewportEl).width) - : this._sizes.viewportOffsetHeight !== parseFloat(_Global.getComputedStyle(this._viewportEl).height); - if (!viewportResized) { return; } - - this._measured = false; - - if (!this._pendingResize) { - this._pendingResize = true; - - this._resizeImplBound = this._resizeImplBound || this._resizeImpl.bind(this); - - this._updateAppBarReference(); - - if (this._appBarEl && this._appBarEl.winControl && !this._appBarEl.winControl.opened) { - // Do resize lazily. - Scheduler.schedule(this._resizeImplBound, Scheduler.Priority.idle, null, "WinJS.UI.NavBarContainer._resizeImpl"); - this._appBarEl.addEventListener('beforeopen', this._resizeImplBound); - } else { - // Do resize now - this._resizeImpl(); - } - } - }, - - _resizeImpl: function NavBarContainer_resizeImpl() { - if (!this._disposed && this._pendingResize) { - this._pendingResize = false; - if (this._appBarEl) { - this._appBarEl.removeEventListener('beforeopen', this._resizeImplBound); - } - - this._keyboardBehavior.currentIndex = 0; - if (this.element.contains(_Global.document.activeElement)) { - this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex); - } - this._closeSplitIfOpen(); - this._ensureVisible(this._keyboardBehavior.currentIndex, true); - this._updatePageUI(); - } - }, - - _keyDownHandler: function NavBarContainer_keyDownHandler(ev) { - var keyCode = ev.keyCode; - if (!ev.altKey && (keyCode === Key.pageUp || keyCode === Key.pageDown)) { - var srcElement = ev.target; - if (_ElementUtilities._matchesSelector(srcElement, ".win-interactive, .win-interactive *")) { - return; - } - - var index = this._keyboardBehavior.currentIndex; - this._measure(); - - var sizes = this._sizes; - var page = Math.floor(index / (sizes.columnsPerPage * sizes.rowsPerPage)); - - var scrollPositionTarget = null; - if (keyCode === Key.pageUp) { - if (this.layout === _UI.Orientation.horizontal) { - var indexOfFirstItemOnPage = page * sizes.columnsPerPage * sizes.rowsPerPage; - if (index === indexOfFirstItemOnPage && this._surfaceEl.children[index].winControl._buttonEl === _Global.document.activeElement) { - // First item on page so go back 1 page. - index = index - sizes.columnsPerPage * sizes.rowsPerPage; - } else { - // Not first item on page so go to the first item on page. - index = indexOfFirstItemOnPage; - } - } else { - var currentItem = this._surfaceEl.children[index]; - var top = currentItem.offsetTop; - var bottom = top + currentItem.offsetHeight; - var scrollPosition = this._zooming ? this._zoomPosition : this._scrollPosition; - - if (top >= scrollPosition && bottom < scrollPosition + sizes.viewportOffsetHeight) { - // current item is fully on screen. - while (index > 0 && - this._surfaceEl.children[index - 1].offsetTop > scrollPosition) { - index--; - } - } - - if (this._keyboardBehavior.currentIndex === index) { - var scrollPositionForOnePageAboveItem = bottom - sizes.viewportOffsetHeight; - index = Math.max(0, index - 1); - while (index > 0 && - this._surfaceEl.children[index - 1].offsetTop > scrollPositionForOnePageAboveItem) { - index--; - } - if (index > 0) { - scrollPositionTarget = this._surfaceEl.children[index].offsetTop - this._sizes.itemMarginTop; - } else { - scrollPositionTarget = 0; - } - } - } - - index = Math.max(index, 0); - this._keyboardBehavior.currentIndex = index; - - var element = this._surfaceEl.children[index].winControl._buttonEl; - - if (scrollPositionTarget !== null) { - this._scrollTo(scrollPositionTarget); - } - - _ElementUtilities._setActive(element, this._viewportEl); - } else { - if (this.layout === _UI.Orientation.horizontal) { - var indexOfLastItemOnPage = (page + 1) * sizes.columnsPerPage * sizes.rowsPerPage - 1; - - if (index === indexOfLastItemOnPage) { - // Last item on page so go forward 1 page. - index = index + sizes.columnsPerPage * sizes.rowsPerPage; - } else { - // Not Last item on page so go to last item on page. - index = indexOfLastItemOnPage; - } - } else { - var currentItem = this._surfaceEl.children[this._keyboardBehavior.currentIndex]; - var top = currentItem.offsetTop; - var bottom = top + currentItem.offsetHeight; - var scrollPosition = this._zooming ? this._zoomPosition : this._scrollPosition; - - if (top >= scrollPosition && bottom < scrollPosition + sizes.viewportOffsetHeight) { - // current item is fully on screen. - while (index < this._surfaceEl.children.length - 1 && - this._surfaceEl.children[index + 1].offsetTop + this._surfaceEl.children[index + 1].offsetHeight < scrollPosition + sizes.viewportOffsetHeight) { - index++; - } - } - - if (index === this._keyboardBehavior.currentIndex) { - var scrollPositionForOnePageBelowItem = top + sizes.viewportOffsetHeight; - index = Math.min(this._surfaceEl.children.length - 1, index + 1); - while (index < this._surfaceEl.children.length - 1 && - this._surfaceEl.children[index + 1].offsetTop + this._surfaceEl.children[index + 1].offsetHeight < scrollPositionForOnePageBelowItem) { - index++; - } - - if (index < this._surfaceEl.children.length - 1) { - scrollPositionTarget = this._surfaceEl.children[index + 1].offsetTop - this._sizes.viewportOffsetHeight; - } else { - scrollPositionTarget = this._scrollLength - this._sizes.viewportOffsetHeight; - } - } - } - - index = Math.min(index, this._surfaceEl.children.length - 1); - this._keyboardBehavior.currentIndex = index; - - var element = this._surfaceEl.children[index].winControl._buttonEl; - - if (scrollPositionTarget !== null) { - this._scrollTo(scrollPositionTarget); - } - - try { - _ElementUtilities._setActive(element, this._viewportEl); - } catch (e) { - } - } - } - }, - - _focusHandler: function NavBarContainer_focusHandler(ev) { - var srcElement = ev.target; - if (!this._surfaceEl.contains(srcElement)) { - // Forward focus from NavBarContainer, viewport or surface to the currentIndex. - this._skipEnsureVisible = true; - this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex); - } - }, - - _itemsFocusHandler: function NavBarContainer_itemsFocusHandler(ev) { - // Find the item which is being focused and scroll it to view. - var srcElement = ev.target; - if (srcElement === this._surfaceEl) { - return; - } - - while (srcElement.parentNode !== this._surfaceEl) { - srcElement = srcElement.parentNode; - } - - var index = -1; - while (srcElement) { - index++; - srcElement = srcElement.previousSibling; - } - - if (this._skipEnsureVisible) { - this._skipEnsureVisible = false; - } else { - this._ensureVisible(index); - } - }, - - _ensureVisible: function NavBarContainer_ensureVisible(index, withoutAnimation) { - this._measure(); - - if (this.layout === _UI.Orientation.horizontal) { - var page = Math.floor(index / (this._sizes.rowsPerPage * this._sizes.columnsPerPage)); - this._scrollTo(page * this._sizes.viewportOffsetWidth, withoutAnimation); - } else { - var element = this._surfaceEl.children[index]; - var maxScrollPosition; - if (index > 0) { - maxScrollPosition = element.offsetTop - this._sizes.itemMarginTop; - } else { - maxScrollPosition = 0; - } - var minScrollPosition; - if (index < this._surfaceEl.children.length - 1) { - minScrollPosition = this._surfaceEl.children[index + 1].offsetTop - this._sizes.viewportOffsetHeight; - } else { - minScrollPosition = this._scrollLength - this._sizes.viewportOffsetHeight; - } - - var newScrollPosition = this._zooming ? this._zoomPosition : this._scrollPosition; - newScrollPosition = Math.max(newScrollPosition, minScrollPosition); - newScrollPosition = Math.min(newScrollPosition, maxScrollPosition); - this._scrollTo(newScrollPosition, withoutAnimation); - } - }, - - _scrollTo: function NavBarContainer_scrollTo(targetScrollPosition, withoutAnimation) { - this._measure(); - if (this.layout === _UI.Orientation.horizontal) { - targetScrollPosition = Math.max(0, Math.min(this._scrollLength - this._sizes.viewportOffsetWidth, targetScrollPosition)); - } else { - targetScrollPosition = Math.max(0, Math.min(this._scrollLength - this._sizes.viewportOffsetHeight, targetScrollPosition)); - } - - if (withoutAnimation) { - if (Math.abs(this._scrollPosition - targetScrollPosition) > 1) { - this._zooming = false; - - this._scrollPosition = targetScrollPosition; - this._updatePageUI(); - if (!this._duringForceLayout) { - this._closeSplitIfOpen(); - } - - var newScrollPos = {}; - newScrollPos[(this.layout === _UI.Orientation.horizontal ? "scrollLeft" : "scrollTop")] = targetScrollPosition; - _ElementUtilities.setScrollPosition(this._viewportEl, newScrollPos); - } - } else { - if ((!this._zooming && Math.abs(this._scrollPosition - targetScrollPosition) > 1) || (this._zooming && Math.abs(this._zoomPosition - targetScrollPosition) > 1)) { - this._zoomPosition = targetScrollPosition; - - this._zooming = true; - - if (this.layout === _UI.Orientation.horizontal) { - this._viewportEl.style.msScrollSnapType = "none"; - _ElementUtilities._zoomTo(this._viewportEl, { contentX: targetScrollPosition, contentY: 0, viewportX: 0, viewportY: 0 }); - } else { - _ElementUtilities._zoomTo(this._viewportEl, { contentX: 0, contentY: targetScrollPosition, viewportX: 0, viewportY: 0 }); - } - - this._closeSplitIfOpen(); - } - } - }, - - _MSManipulationStateChangedHandler: function NavBarContainer_MSManipulationStateChangedHandler(e) { - this._currentManipulationState = e.currentState; - - if (e.currentState === e.MS_MANIPULATION_STATE_ACTIVE) { - this._viewportEl.style.msScrollSnapType = ""; - this._zooming = false; - } - - _Global.clearTimeout(this._manipulationStateTimeoutId); - // The extra stop event is firing when an zoomTo is called during another zoomTo and - // also the first zoomTo after a resize. - if (e.currentState === e.MS_MANIPULATION_STATE_STOPPED) { - this._manipulationStateTimeoutId = _Global.setTimeout(function () { - this._viewportEl.style.msScrollSnapType = ""; - this._zooming = false; - this._updateCurrentIndexIfPageChanged(); - }.bind(this), 100); - } - }, - - _scrollHandler: function NavBarContainer_scrollHandler() { - if (this._disposed) { return; } - - this._measured = false; - if (!this._checkingScroll) { - var that = this; - this._checkingScroll = _BaseUtils._requestAnimationFrame(function () { - if (that._disposed) { return; } - that._checkingScroll = null; - - var newScrollPosition = _ElementUtilities.getScrollPosition(that._viewportEl)[(that.layout === _UI.Orientation.horizontal ? "scrollLeft" : "scrollTop")]; - if (newScrollPosition !== that._scrollPosition) { - that._scrollPosition = newScrollPosition; - that._closeSplitIfOpen(); - } - that._updatePageUI(); - - if (!that._zooming && that._currentManipulationState === MS_MANIPULATION_STATE_STOPPED) { - that._updateCurrentIndexIfPageChanged(); - } - }); - } - }, - - _updateCurrentIndexIfPageChanged: function NavBarContainer_updateCurrentIndexIfPageChanged() { - // If you change pages via pagination arrows, mouse wheel, or panning we need to update the current - // item to be the first item on the new page. - if (this.layout === _UI.Orientation.horizontal) { - this._measure(); - var currentPage = this._currentPage; - var firstIndexOnPage = currentPage * this._sizes.rowsPerPage * this._sizes.columnsPerPage; - var lastIndexOnPage = (currentPage + 1) * this._sizes.rowsPerPage * this._sizes.columnsPerPage - 1; - - if (this._keyboardBehavior.currentIndex < firstIndexOnPage || this._keyboardBehavior.currentIndex > lastIndexOnPage) { - // Page change occurred. - this._keyboardBehavior.currentIndex = firstIndexOnPage; - - if (this.element.contains(_Global.document.activeElement)) { - this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex); - } - } - } - }, - - _measure: function NavBarContainer_measure() { - if (!this._measured) { - this._resizeImpl(); - this._writeProfilerMark("measure,StartTM"); - - var sizes = this._sizes; - - sizes.rtl = _Global.getComputedStyle(this._element).direction === "rtl"; - - var itemCount = this._surfaceEl.children.length; - if (itemCount > 0) { - if (!this._sizes.itemMeasured) { - this._writeProfilerMark("measureItem,StartTM"); - - var elementToMeasure = this._surfaceEl.firstElementChild; - // Clear inline margins set by NavBarContainer before measuring. - elementToMeasure.style.margin = ""; - elementToMeasure.style.width = ""; - var elementComputedStyle = _Global.getComputedStyle(elementToMeasure); - sizes.itemOffsetWidth = parseFloat(_Global.getComputedStyle(elementToMeasure).width); - if (elementToMeasure.offsetWidth === 0) { - sizes.itemOffsetWidth = 0; - } - sizes.itemMarginLeft = parseFloat(elementComputedStyle.marginLeft); - sizes.itemMarginRight = parseFloat(elementComputedStyle.marginRight); - sizes.itemWidth = sizes.itemOffsetWidth + sizes.itemMarginLeft + sizes.itemMarginRight; - sizes.itemOffsetHeight = parseFloat(_Global.getComputedStyle(elementToMeasure).height); - if (elementToMeasure.offsetHeight === 0) { - sizes.itemOffsetHeight = 0; - } - sizes.itemMarginTop = parseFloat(elementComputedStyle.marginTop); - sizes.itemMarginBottom = parseFloat(elementComputedStyle.marginBottom); - sizes.itemHeight = sizes.itemOffsetHeight + sizes.itemMarginTop + sizes.itemMarginBottom; - if (sizes.itemOffsetWidth > 0 && sizes.itemOffsetHeight > 0) { - sizes.itemMeasured = true; - } - this._writeProfilerMark("measureItem,StopTM"); - } - - sizes.viewportOffsetWidth = parseFloat(_Global.getComputedStyle(this._viewportEl).width); - if (this._viewportEl.offsetWidth === 0) { - sizes.viewportOffsetWidth = 0; - } - sizes.viewportOffsetHeight = parseFloat(_Global.getComputedStyle(this._viewportEl).height); - if (this._viewportEl.offsetHeight === 0) { - sizes.viewportOffsetHeight = 0; - } - - if (sizes.viewportOffsetWidth === 0 || sizes.itemOffsetHeight === 0) { - this._measured = false; - } else { - this._measured = true; - } - - if (this.layout === _UI.Orientation.horizontal) { - this._scrollPosition = _ElementUtilities.getScrollPosition(this._viewportEl).scrollLeft; - - sizes.leadingEdge = this._leftArrowEl.offsetWidth + parseInt(_Global.getComputedStyle(this._leftArrowEl).marginLeft) + parseInt(_Global.getComputedStyle(this._leftArrowEl).marginRight); - var usableSpace = sizes.viewportOffsetWidth - sizes.leadingEdge * 2; - sizes.maxColumns = sizes.itemWidth ? Math.max(1, Math.floor(usableSpace / sizes.itemWidth)) : 1; - sizes.rowsPerPage = Math.min(this.maxRows, Math.ceil(itemCount / sizes.maxColumns)); - sizes.columnsPerPage = Math.min(sizes.maxColumns, itemCount); - sizes.pages = Math.ceil(itemCount / (sizes.columnsPerPage * sizes.rowsPerPage)); - sizes.trailingEdge = sizes.leadingEdge; - sizes.extraSpace = usableSpace - (sizes.columnsPerPage * sizes.itemWidth); - - this._scrollLength = sizes.viewportOffsetWidth * sizes.pages; - - this._keyboardBehavior.fixedSize = sizes.rowsPerPage; - this._keyboardBehavior.fixedDirection = _KeyboardBehavior._KeyboardBehavior.FixedDirection.height; - - this._surfaceEl.style.height = (sizes.itemHeight * sizes.rowsPerPage) + "px"; - this._surfaceEl.style.width = this._scrollLength + "px"; - } else { - this._scrollPosition = this._viewportEl.scrollTop; - - sizes.leadingEdge = 0; - sizes.rowsPerPage = itemCount; - sizes.columnsPerPage = 1; - sizes.pages = 1; - sizes.trailingEdge = 0; - - // Reminder there is margin collapsing so just use scrollHeight instead of itemHeight * itemCount - this._scrollLength = this._viewportEl.scrollHeight; - - this._keyboardBehavior.fixedSize = sizes.columnsPerPage; - this._keyboardBehavior.fixedDirection = _KeyboardBehavior._KeyboardBehavior.FixedDirection.width; - - this._surfaceEl.style.height = ""; - this._surfaceEl.style.width = ""; - } - - this._updateGridStyles(); - } else { - sizes.pages = 1; - this._hasPreviousContent = false; - this._hasNextContent = false; - this._surfaceEl.style.height = ""; - this._surfaceEl.style.width = ""; - } - - this._writeProfilerMark("measure,StopTM"); - } - }, - - _updateGridStyles: function NavBarContainer_updateGridStyles() { - var sizes = this._sizes; - var itemCount = this._surfaceEl.children.length; - - for (var index = 0; index < itemCount; index++) { - var itemEl = this._surfaceEl.children[index]; - - var marginRight; - var marginLeft; - var width = ""; - - if (this.layout === _UI.Orientation.horizontal) { - var column = Math.floor(index / sizes.rowsPerPage); - var isFirstColumnOnPage = column % sizes.columnsPerPage === 0; - var isLastColumnOnPage = column % sizes.columnsPerPage === sizes.columnsPerPage - 1; - - var extraTrailingMargin = sizes.trailingEdge; - if (this.fixedSize) { - extraTrailingMargin += sizes.extraSpace; - } else { - var spaceToDistribute = sizes.extraSpace - (sizes.maxColumns - sizes.columnsPerPage) * sizes.itemWidth; - width = (sizes.itemOffsetWidth + (spaceToDistribute / sizes.maxColumns)) + "px"; - } - - var extraMarginRight; - var extraMarginLeft; - - if (sizes.rtl) { - extraMarginRight = (isFirstColumnOnPage ? sizes.leadingEdge : 0); - extraMarginLeft = (isLastColumnOnPage ? extraTrailingMargin : 0); - } else { - extraMarginRight = (isLastColumnOnPage ? extraTrailingMargin : 0); - extraMarginLeft = (isFirstColumnOnPage ? sizes.leadingEdge : 0); - } - - marginRight = extraMarginRight + sizes.itemMarginRight + "px"; - marginLeft = extraMarginLeft + sizes.itemMarginLeft + "px"; - } else { - marginRight = ""; - marginLeft = ""; - } - - if (itemEl.style.marginRight !== marginRight) { - itemEl.style.marginRight = marginRight; - } - if (itemEl.style.marginLeft !== marginLeft) { - itemEl.style.marginLeft = marginLeft; - } - if (itemEl.style.width !== width) { - itemEl.style.width = width; - } - } - }, - - _updatePageUI: function NavBarContainer_updatePageUI() { - this._measure(); - var currentPage = this._currentPage; - - this._hasPreviousContent = (currentPage !== 0); - this._hasNextContent = (currentPage < this._sizes.pages - 1); - this._updateArrows(); - - // Always output the pagination indicators so they reserves up space. - if (this._indicatorCount !== this._sizes.pages) { - this._indicatorCount = this._sizes.pages; - this._pageindicatorsEl.innerHTML = new Array(this._sizes.pages + 1).join(''); - } - - for (var i = 0; i < this._pageindicatorsEl.children.length; i++) { - if (i === currentPage) { - _ElementUtilities.addClass(this._pageindicatorsEl.children[i], NavBarContainer._ClassName.currentindicator); - } else { - _ElementUtilities.removeClass(this._pageindicatorsEl.children[i], NavBarContainer._ClassName.currentindicator); - } - } - - if (this._sizes.pages > 1) { - this._viewportEl.style.overflowX = this._panningDisabled ? "hidden" : ""; - this._pageindicatorsEl.style.visibility = ""; - } else { - this._viewportEl.style.overflowX = "hidden"; - this._pageindicatorsEl.style.visibility = "hidden"; - } - - if (this._sizes.pages <= 1 || this._layout !== _UI.Orientation.horizontal) { - this._ariaStartMarker.removeAttribute("aria-flowto"); - this._ariaEndMarker.removeAttribute("x-ms-aria-flowfrom"); - } else { - var firstIndexOnCurrentPage = currentPage * this._sizes.rowsPerPage * this._sizes.columnsPerPage; - var firstItem = this._surfaceEl.children[firstIndexOnCurrentPage].winControl._buttonEl; - _ElementUtilities._ensureId(firstItem); - this._ariaStartMarker.setAttribute("aria-flowto", firstItem.id); - - var lastIndexOnCurrentPage = Math.min(this._surfaceEl.children.length - 1, (currentPage + 1) * this._sizes.rowsPerPage * this._sizes.columnsPerPage - 1); - var lastItem = this._surfaceEl.children[lastIndexOnCurrentPage].winControl._buttonEl; - _ElementUtilities._ensureId(lastItem); - this._ariaEndMarker.setAttribute("x-ms-aria-flowfrom", lastItem.id); - } - }, - - _closeSplitIfOpen: function NavBarContainer_closeSplitIfOpen() { - if (this._currentSplitNavItem) { - if (this._currentSplitNavItem.splitOpened) { - this._currentSplitNavItem._toggleSplit(); - } - this._currentSplitNavItem = null; - } - }, - - _updateArrows: function NavBarContainer_updateArrows() { - var hasLeftContent = this._sizes.rtl ? this._hasNextContent : this._hasPreviousContent; - var hasRightContent = this._sizes.rtl ? this._hasPreviousContent : this._hasNextContent; - - var that = this; - // Previous and next are the arrows, not states. On mouse hover the arrows fade in immediately. If you - // mouse out the arrows fade out after a delay. When you reach the last/first page, the corresponding - // arrow fades out immediately as well. - if ((this._mouseInViewport || this._panningDisabled) && hasLeftContent) { - this._leftArrowWaitingToFadeOut && this._leftArrowWaitingToFadeOut.cancel(); - this._leftArrowWaitingToFadeOut = null; - this._leftArrowFadeOut && this._leftArrowFadeOut.cancel(); - this._leftArrowFadeOut = null; - this._leftArrowEl.style.visibility = ''; - this._leftArrowFadeIn = this._leftArrowFadeIn || Animations.fadeIn(this._leftArrowEl); - } else { - if (hasLeftContent) { - // If we need a delayed fade out and we are already running a delayed fade out just use that one, don't extend it. - // Otherwise create a delayed fade out. - this._leftArrowWaitingToFadeOut = this._leftArrowWaitingToFadeOut || Promise.timeout(_TransitionAnimation._animationTimeAdjustment(buttonFadeDelay)); - } else { - // If we need a immediate fade out and already have a delayed fade out cancel that one and create an immediate one. - this._leftArrowWaitingToFadeOut && this._leftArrowWaitingToFadeOut.cancel(); - this._leftArrowWaitingToFadeOut = Promise.wrap(); - } - this._leftArrowWaitingToFadeOut.then(function () { - // After the delay cancel any fade in if running. If we already were fading out continue it otherwise start the fade out. - this._leftArrowFadeIn && this._leftArrowFadeIn.cancel(); - this._leftArrowFadeIn = null; - this._leftArrowFadeOut = this._leftArrowFadeOut || Animations.fadeOut(this._leftArrowEl).then(function () { - that._leftArrowEl.style.visibility = 'hidden'; - }); - }.bind(this)); - } - - // Same pattern for Next arrow. - if ((this._mouseInViewport || this._panningDisabled) && hasRightContent) { - this._rightArrowWaitingToFadeOut && this._rightArrowWaitingToFadeOut.cancel(); - this._rightArrowWaitingToFadeOut = null; - this._rightArrowFadeOut && this._rightArrowFadeOut.cancel(); - this._rightArrowFadeOut = null; - this._rightArrowEl.style.visibility = ''; - this._rightArrowFadeIn = this._rightArrowFadeIn || Animations.fadeIn(this._rightArrowEl); - } else { - if (hasRightContent) { - this._rightArrowWaitingToFadeOut = this._rightArrowWaitingToFadeOut || Promise.timeout(_TransitionAnimation._animationTimeAdjustment(buttonFadeDelay)); - } else { - this._rightArrowWaitingToFadeOut && this._rightArrowWaitingToFadeOut.cancel(); - this._rightArrowWaitingToFadeOut = Promise.wrap(); - } - this._rightArrowWaitingToFadeOut.then(function () { - this._rightArrowFadeIn && this._rightArrowFadeIn.cancel(); - this._rightArrowFadeIn = null; - this._rightArrowFadeOut = this._rightArrowFadeOut || Animations.fadeOut(this._rightArrowEl).then(function () { - that._rightArrowEl.style.visibility = 'hidden'; - }); - }.bind(this)); - } - }, - - _navbarCommandInvokedHandler: function NavBarContainer_navbarCommandInvokedHandler(ev) { - var srcElement = ev.target; - var index = -1; - while (srcElement) { - index++; - srcElement = srcElement.previousSibling; - } - - this._fireEvent(NavBarContainer._EventName.invoked, { - index: index, - navbarCommand: ev.target.winControl, - data: this._repeater ? this._repeater.data.getAt(index) : null - }); - }, - - _navbarCommandSplitToggleHandler: function NavBarContainer_navbarCommandSplitToggleHandler(ev) { - var srcElement = ev.target; - var index = -1; - while (srcElement) { - index++; - srcElement = srcElement.previousSibling; - } - - var navbarCommand = ev.target.winControl; - - this._closeSplitIfOpen(); - - if (navbarCommand.splitOpened) { - this._currentSplitNavItem = navbarCommand; - } - - this._fireEvent(NavBarContainer._EventName.splitToggle, { - opened: navbarCommand.splitOpened, - index: index, - navbarCommand: navbarCommand, - data: this._repeater ? this._repeater.data.getAt(index) : null - }); - }, - - _fireEvent: function NavBarContainer_fireEvent(type, detail) { - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(type, true, false, detail); - this.element.dispatchEvent(event); - }, - - _writeProfilerMark: function NavBarContainer_writeProfilerMark(text) { - var message = "WinJS.UI.NavBarContainer:" + this._id + ":" + text; - _WriteProfilerMark(message); - _Log.log && _Log.log(message, null, "navbarcontainerprofiler"); - }, - - dispose: function NavBarContainer_dispose() { - /// - /// - /// Disposes this control. - /// - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - - if (this._appBarEl) { - this._appBarEl.removeEventListener('beforeopen', this._closeSplitAndResetBound); - this._appBarEl.removeEventListener('beforeopen', this._resizeImplBound); - } - - Navigation.removeEventListener('navigated', this._closeSplitAndResetBound); - - this._leftArrowWaitingToFadeOut && this._leftArrowWaitingToFadeOut.cancel(); - this._leftArrowFadeOut && this._leftArrowFadeOut.cancel(); - this._leftArrowFadeIn && this._leftArrowFadeIn.cancel(); - this._rightArrowWaitingToFadeOut && this._rightArrowWaitingToFadeOut.cancel(); - this._rightArrowFadeOut && this._rightArrowFadeOut.cancel(); - this._rightArrowFadeIn && this._rightArrowFadeIn.cancel(); - - _ElementUtilities._resizeNotifier.unsubscribe(this._element, this._boundResizeHandler); - - this._removeDataChangingEvents(); - this._removeDataChangedEvents(); - } - }, { - // Names of classes used by the NavBarContainer. - _ClassName: { - navbarcontainer: "win-navbarcontainer", - pageindicators: "win-navbarcontainer-pageindicator-box", - indicator: "win-navbarcontainer-pageindicator", - currentindicator: "win-navbarcontainer-pageindicator-current", - vertical: "win-navbarcontainer-vertical", - horizontal: "win-navbarcontainer-horizontal", - viewport: "win-navbarcontainer-viewport", - surface: "win-navbarcontainer-surface", - navarrow: "win-navbarcontainer-navarrow", - navleftarrow: "win-navbarcontainer-navleft", - navrightarrow: "win-navbarcontainer-navright" - }, - _EventName: { - invoked: eventNames.invoked, - splitToggle: eventNames.splittoggle - } - }); - _Base.Class.mix(NavBarContainer, _Control.DOMEventMixin); - return NavBarContainer; - }) - }); - -}); - - -define('require-style!less/styles-navbar',[],function(){}); - -define('require-style!less/colors-navbar',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/NavBar',[ - '../Core/_Global', - '../Core/_WinRT', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_Events', - '../Core/_WriteProfilerMark', - '../Promise', - '../Scheduler', - '../Utilities/_ElementUtilities', - '../Utilities/_Hoverable', - "../_Accents", - './_LegacyAppBar', - './NavBar/_Command', - './NavBar/_Container', - 'require-style!less/styles-navbar', - 'require-style!less/colors-navbar' -], function NavBarInit(_Global,_WinRT, _Base, _BaseUtils, _Events, _WriteProfilerMark, Promise, Scheduler, _ElementUtilities, _Hoverable, _Accents, _LegacyAppBar, _Command, _Container) { - "use strict"; - - _Accents.createAccentRule("html.win-hoverable .win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened:hover", [{ name: "background-color", value: _Accents.ColorTypes.listSelectHover }]); - _Accents.createAccentRule("html.win-hoverable .win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened:hover.win-pressed", [{ name: "background-color", value: _Accents.ColorTypes.listSelectPress }]); - _Accents.createAccentRule(".win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened", [{ name: "background-color", value: _Accents.ColorTypes.listSelectRest }]); - _Accents.createAccentRule(".win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened.win-pressed", [{ name: "background-color", value: _Accents.ColorTypes.listSelectPress }]); - - var customLayout = "custom"; - - _Base.Namespace.define("WinJS.UI", { - /// - /// - /// Displays navigation commands in a toolbar that the user can open or close. - /// - /// - /// - /// - /// - /// - ///
- ///
- ///
- /// ]]>
- /// Raised just before opening the NavBar. - /// Raised immediately after an NavBar is fully opened. - /// Raised just before closing the NavBar. - /// Raised immediately after the NavBar is fully closed. - /// Fired when children of NavBar control have been processed from a WinJS.UI.processAll call. - /// Styles the entire NavBar. - /// - /// - NavBar: _Base.Namespace._lazy(function () { - var childrenProcessedEventName = "childrenprocessed"; - var createEvent = _Events._createEventProperty; - - var NavBar = _Base.Class.derive(_LegacyAppBar._LegacyAppBar, function NavBar_ctor(element, options) { - /// - /// - /// Creates a new NavBar. - /// - /// - /// The DOM element that will host the new NavBar control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's - /// properties or events. - /// - /// - /// The new NavBar control. - /// - /// - /// - - options = options || {}; - - // Shallow copy object so we can modify it. - options = _BaseUtils._shallowCopy(options); - - // Default to Placement = Top and Layout = Custom - options.placement = options.placement || "top"; - options.layout = customLayout; - options.closedDisplayMode = options.closedDisplayMode || "minimal"; - - _LegacyAppBar._LegacyAppBar.call(this, element, options); - - this._element.addEventListener("beforeopen", this._handleBeforeShow.bind(this)); - - _ElementUtilities.addClass(this.element, NavBar._ClassName.navbar); - - if (_WinRT.Windows.ApplicationModel.DesignMode.designModeEnabled) { - this._processChildren(); - } else { - Scheduler.schedule(this._processChildren.bind(this), Scheduler.Priority.idle, null, "WinJS.UI.NavBar.processChildren"); - } - }, { - - // Restrict values of closedDisplayMode to 'none' or 'minimal' - - /// - /// Gets/Sets how NavBar will display itself while hidden. Values are "none" and "minimal". - /// - closedDisplayMode: { - get: function () { - return this._closedDisplayMode; - }, - set: function (value) { - var newValue = (value === "none" ? "none" : "minimal"); - Object.getOwnPropertyDescriptor(_LegacyAppBar._LegacyAppBar.prototype, "closedDisplayMode").set.call(this, newValue); - this._closedDisplayMode = newValue; - }, - }, - - /// - /// Raised when children of NavBar control have been processed by a WinJS.UI.processAll call. - /// - /// - onchildrenprocessed: createEvent(childrenProcessedEventName), - - _processChildren: function NavBar_processChildren() { - // The NavBar control schedules processAll on its children at idle priority to avoid hurting startup - // performance. If the NavBar is shown before the scheduler gets to the idle job, the NavBar will - // immediately call processAll on its children. If your app needs the children to be processed before - // the scheduled job executes, you may call processChildren to force the processAll call. - if (!this._processed) { - this._processed = true; - - this._writeProfilerMark("processChildren,StartTM"); - var that = this; - var processed = Promise.as(); - if (this._processors) { - this._processors.forEach(function (processAll) { - for (var i = 0, len = that.element.children.length; i < len; i++) { - (function (child) { - processed = processed.then(function () { - processAll(child); - }); - }(that.element.children[i])); - } - }); - } - return processed.then( - function () { - that._writeProfilerMark("processChildren,StopTM"); - that._fireEvent(NavBar._EventName.childrenProcessed); - }, - function () { - that._writeProfilerMark("processChildren,StopTM"); - that._fireEvent(NavBar._EventName.childrenProcessed); - } - ); - } - return Promise.wrap(); - }, - - _show: function NavBar_show() { - // Override _show to call processChildren first. - // - if (this.disabled) { - return; - } - var that = this; - this._processChildren().then(function () { - _LegacyAppBar._LegacyAppBar.prototype._show.call(that); - }); - }, - - _handleBeforeShow: function NavBar_handleBeforeShow() { - // Navbar needs to ensure its elements to have their correct height and width after _LegacyAppBar changes display="none" - // to display="" and _LegacyAppBar needs the elements to have their final height before it measures its own element height - // to do the slide in animation over the correct amount of pixels. - if (this._disposed) { - return; - } - - var navbarcontainerEls = this.element.querySelectorAll('.win-navbarcontainer'); - for (var i = 0; i < navbarcontainerEls.length; i++) { - navbarcontainerEls[i].winControl.forceLayout(); - } - }, - - _fireEvent: function NavBar_fireEvent(type, detail) { - var event = _Global.document.createEvent("CustomEvent"); - event.initCustomEvent(type, true, false, detail || {}); - this.element.dispatchEvent(event); - }, - - _writeProfilerMark: function NavBar_writeProfilerMark(text) { - _WriteProfilerMark("WinJS.UI.NavBar:" + this._id + ":" + text); - } - }, { - _ClassName: { - navbar: "win-navbar" - }, - _EventName: { - childrenProcessed: childrenProcessedEventName - }, - isDeclarativeControlContainer: _BaseUtils.markSupportedForProcessing(function (navbar, callback) { - if (navbar._processed) { - for (var i = 0, len = navbar.element.children.length; i < len; i++) { - callback(navbar.element.children[i]); - } - } else { - navbar._processors = navbar._processors || []; - navbar._processors.push(callback); - } - }) - }); - - return NavBar; - }) - }); - -}); - -define('require-style!less/styles-viewbox',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -// ViewBox control -define('WinJS/Controls/ViewBox',[ - '../Core/_Global', - '../Core/_Base', - '../Core/_BaseUtils', - '../Core/_ErrorFromName', - '../Core/_Resources', - '../Scheduler', - '../Utilities/_Control', - '../Utilities/_Dispose', - '../Utilities/_ElementUtilities', - '../Utilities/_Hoverable', - 'require-style!less/styles-viewbox' - ], function viewboxInit(_Global, _Base, _BaseUtils, _ErrorFromName, _Resources, Scheduler, _Control, _Dispose, _ElementUtilities, _Hoverable) { - "use strict"; - - _Base.Namespace.define("WinJS.UI", { - /// - /// - /// Scales a single child element to fill the available space without - /// resizing it. This control reacts to changes in the size of the container as well as - /// changes in size of the child element. For example, a media query may result in - /// a change in aspect ratio. - /// - /// - /// View Box - /// - /// - ///
ViewBox
]]>
- /// - /// - ViewBox: _Base.Namespace._lazy(function () { - - var strings = { - get invalidViewBoxChildren() { return "ViewBox expects to only have one child element"; }, - }; - - function onresize(control) { - if (control && !control._resizing) { - control._resizing = control._resizing || 0; - control._resizing++; - try { - control._updateLayout(); - } finally { - control._resizing--; - } - } - } - - function onresizeBox(ev) { - if (ev.target) { - onresize(ev.target.winControl); - } - } - - function onresizeSizer(ev) { - if (ev.target) { - onresize(ev.target.parentElement.winControl); - } - } - - var ViewBox = _Base.Class.define(function ViewBox_ctor(element) { - /// - /// Initializes a new instance of the ViewBox control - /// - /// The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. - /// - /// - /// The set of options to be applied initially to the ViewBox control. - /// - /// A constructed ViewBox control. - /// - this._disposed = false; - - this._element = element || _Global.document.createElement("div"); - var box = this.element; - box.winControl = this; - _ElementUtilities.addClass(box, "win-disposable"); - _ElementUtilities.addClass(box, "win-viewbox"); - this.forceLayout(); - }, { - _sizer: null, - _element: null, - - /// - element: { - get: function () { return this._element; } - }, - - _rtl: { - get: function () { - return _Global.getComputedStyle(this.element).direction === "rtl"; - } - }, - - _initialize: function () { - var box = this.element; - if (box.firstElementChild !== this._sizer) { - if (_BaseUtils.validation) { - if (box.childElementCount !== 1) { - throw new _ErrorFromName("WinJS.UI.ViewBox.InvalidChildren", strings.invalidViewBoxChildren); - } - } - if (this._sizer) { - this._sizer.onresize = null; - } - var sizer = box.firstElementChild; - this._sizer = sizer; - if (sizer) { - _ElementUtilities._resizeNotifier.subscribe(box, onresizeBox); - box.addEventListener("mselementresize", onresizeBox); - _ElementUtilities._resizeNotifier.subscribe(sizer, onresizeSizer); - sizer.addEventListener("mselementresize", onresizeSizer); - } - if (box.clientWidth === 0 && box.clientHeight === 0) { - var that = this; - // Wait for the viewbox to get added to the DOM. It should be added - // in the synchronous block in which _initialize was called. - Scheduler.schedule(function ViewBox_async_initialize() { - that._updateLayout(); - }, Scheduler.Priority.normal, null, "WinJS.UI.ViewBox._updateLayout"); - } - } - }, - _updateLayout: function () { - var sizer = this._sizer; - if (sizer) { - var box = this.element; - var w = sizer.clientWidth; - var h = sizer.clientHeight; - var bw = box.clientWidth; - var bh = box.clientHeight; - var wRatio = bw / w; - var hRatio = bh / h; - var mRatio = Math.min(wRatio, hRatio); - var transX = Math.abs(bw - (w * mRatio)) / 2; - var transY = Math.abs(bh - (h * mRatio)) / 2; - var rtl = this._rtl; - this._sizer.style[_BaseUtils._browserStyleEquivalents["transform"].scriptName] = "translate(" + (rtl ? "-" : "") + transX + "px," + transY + "px) scale(" + mRatio + ")"; - this._sizer.style[_BaseUtils._browserStyleEquivalents["transform-origin"].scriptName] = rtl ? "top right" : "top left"; - } - }, - - dispose: function () { - /// - /// - /// Disposes this ViewBox. - /// - /// - if (this._disposed) { - return; - } - - if (this.element) { - _ElementUtilities._resizeNotifier.unsubscribe(this.element, onresizeBox); - } - if (this._sizer) { - _ElementUtilities._resizeNotifier.unsubscribe(this._sizer, onresizeSizer); - } - - this._disposed = true; - _Dispose.disposeSubTree(this._element); - }, - - forceLayout: function () { - this._initialize(); - this._updateLayout(); - } - }); - _Base.Class.mix(ViewBox, _Control.DOMEventMixin); - return ViewBox; - }) - }); - -}); - - -define('require-style!less/styles-contentdialog',[],function(){}); - -define('require-style!less/colors-contentdialog',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('WinJS/Controls/ContentDialog',[ - '../Application', - '../Utilities/_Dispose', - '../_Accents', - '../Promise', - '../_Signal', - '../_LightDismissService', - '../Core/_BaseUtils', - '../Core/_Global', - '../Core/_WinRT', - '../Core/_Base', - '../Core/_Events', - '../Core/_ErrorFromName', - '../Core/_Resources', - '../Utilities/_Control', - '../Utilities/_ElementUtilities', - '../Utilities/_Hoverable', - '../Animations', - 'require-style!less/styles-contentdialog', - 'require-style!less/colors-contentdialog' -], function contentDialogInit(Application, _Dispose, _Accents, Promise, _Signal, _LightDismissService, _BaseUtils, _Global, _WinRT, _Base, _Events, _ErrorFromName, _Resources, _Control, _ElementUtilities, _Hoverable, _Animations) { - "use strict"; - - _Accents.createAccentRule(".win-contentdialog-dialog", [{ name: "outline-color", value: _Accents.ColorTypes.accent }]); - - _Base.Namespace.define("WinJS.UI", { - /// - /// - /// Displays a modal dialog which can display arbitrary HTML content. - /// - /// - /// - /// - /// ]]> - /// Raised just before showing a dialog. Call preventDefault on this event to stop the dialog from being shown. - /// Raised immediately after a dialog is fully shown. - /// Raised just before hiding a dialog. Call preventDefault on this event to stop the dialog from being hidden. - /// Raised immediately after a dialog is fully hidden. - /// The entire ContentDialog control. - /// The full screen element which dims the content that is behind the dialog. - /// The main element of the dialog which holds the dialog's title, content, and commands. - /// The element which displays the dialog's title. - /// The element which contains the dialog's custom content. - /// The element which contains the dialog's primary and secondary commands. - /// The dialog's primary button. - /// The dialog's secondary button. - /// - /// - ContentDialog: _Base.Namespace._lazy(function () { - var Strings = { - get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; }, - get controlDisposed() { return "Cannot interact with the control after it has been disposed"; }, - get contentDialogAlreadyShowing() { return "Cannot show a ContentDialog if there is already a ContentDialog that is showing"; } - }; - var DismissalResult = { - /// - /// The dialog was dismissed without the user selecting any of the commands. The user may have - /// dismissed the dialog by hitting the escape key or pressing the hardware back button. - /// - none: "none", - /// - /// The user dismissed the dialog by pressing the primary command. - /// - primary: "primary", - /// - /// The user dismissed the dialog by pressing the secondary command. - /// - secondary: "secondary" - }; - var ClassNames = { - contentDialog: "win-contentdialog", - backgroundOverlay: "win-contentdialog-backgroundoverlay", - dialog: "win-contentdialog-dialog", - title: "win-contentdialog-title", - content: "win-contentdialog-content", - commands: "win-contentdialog-commands", - primaryCommand: "win-contentdialog-primarycommand", - secondaryCommand: "win-contentdialog-secondarycommand", - - _verticalAlignment: "win-contentdialog-verticalalignment", - _scroller: "win-contentdialog-scroller", - _column0or1: "win-contentdialog-column0or1", - _visible: "win-contentdialog-visible", - _tabStop: "win-contentdialog-tabstop", - _commandSpacer: "win-contentdialog-commandspacer" - }; - var EventNames = { - beforeShow: "beforeshow", - afterShow: "aftershow", - beforeHide: "beforehide", - afterHide: "afterhide", - }; - var minContentHeightWithInputPane = 96; - - // WinJS animation promises always complete successfully. This - // helper allows an animation promise to complete in the canceled state - // so that the success handler can be skipped when the animation is - // interrupted. - function cancelablePromise(animationPromise) { - return Promise._cancelBlocker(animationPromise, function () { - animationPromise.cancel(); - }); - } - - function onInputPaneShown(eventObject) { - /*jshint validthis: true */ - eventObject.ensuredFocusedElementInView = true; - this.dialog._renderForInputPane(eventObject.occludedRect.height); - } - - function onInputPaneHidden() { - /*jshint validthis: true */ - this.dialog._clearInputPaneRendering(); - } - - // Noop function, used in the various states to indicate that they don't support a given - // message. Named with the somewhat cute name '_' because it reads really well in the states. - - function _() { } - - // Implementing the control as a state machine helps us correctly handle: - // - re-entrancy while firing events - // - calls into the control during asynchronous operations (e.g. animations) - // - // Many of the states do their "enter" work within a promise chain. The idea is that if - // the state is interrupted and exits, the rest of its work can be skipped by canceling - // the promise chain. - // An interesting detail is that anytime the state may call into app code (e.g. due to - // firing an event), the current promise must end and a new promise must be chained off of it. - // This is necessary because the app code may interact with the ContentDialog and cause it to - // change states. If we didn't create a new promise, then the very next line of code that runs - // after calling into app code may not be valid because the state may have exited. Starting a - // new promise after each call into app code prevents us from having to worry about this - // problem. In this configuration, when a promise's success handler runs, it guarantees that - // the state hasn't exited. - // For similar reasons, each of the promise chains created in "enter" starts off with a _Signal - // which is completed at the end of the "enter" function (this boilerplate is abstracted away by - // the "interruptible" function). The reason is that we don't want any of the code in "enter" - // to run until the promise chain has been stored in a variable. If we didn't do this (e.g. instead, - // started the promise chain with Promise.wrap()), then the "enter" code could trigger the "exit" - // function (via app code) before the promise chain had been stored in a variable. Under these - // circumstances, the promise chain would be uncancelable and so the "enter" work would be - // unskippable. This wouldn't be good when we needed the state to exit early. - - // These two functions manage interruptible work promises (one creates them the other cancels - // them). They communicate with each other thru the _interruptibleWorkPromises property which - // "interruptible" creates on your object. - - function interruptible(object, workFn) { - object._interruptibleWorkPromises = object._interruptibleWorkPromises || []; - var workStoredSignal = new _Signal(); - object._interruptibleWorkPromises.push(workFn(object, workStoredSignal.promise)); - workStoredSignal.complete(); - } - - function cancelInterruptibles() { - /*jshint validthis: true */ - (this._interruptibleWorkPromises || []).forEach(function (workPromise) { - workPromise.cancel(); - }); - } - - // Transitions: - // When created, the control will take the following initialization transition: - // Init -> Hidden - // Following that, the life of the dialog will be dominated by the following 3 - // sequences of transitions. In geneneral, these sequences are uninterruptible. - // Hidden -> BeforeShow -> Hidden (when preventDefault is called on beforeshow event) - // Hidden -> BeforeShow -> Showing -> Shown - // Shown -> BeforeHide -> Hiding -> Hidden - // Shown -> BeforeHide -> Shown (when preventDefault is called on beforehide event) - // However, any state can be interrupted to go to the Disposed state: - // * -> Disposed - // - // interface IContentDialogState { - // // Debugging - // name: string; - // // State lifecycle - // enter(arg0); - // exit(); - // // ContentDialog's public API surface - // hidden: boolean; - // show(); - // hide(dismissalResult); - // // Events - // onCommandClicked(dismissalResult); - // onInputPaneShown(eventObject); - // onInputPaneHidden(); - // // Provided by _setState for use within the state - // dialog: WinJS.UI.ContentDialog; - // } - - var States = { - // Initial state. Initializes state on the dialog shared by the various states. - Init: _Base.Class.define(null, { - name: "Init", - hidden: true, - enter: function ContentDialog_InitState_enter() { - var dialog = this.dialog; - dialog._dismissable = new _LightDismissService.ModalElement({ - element: dialog._dom.root, - tabIndex: dialog._dom.root.hasAttribute("tabIndex") ? dialog._dom.root.tabIndex : -1, - onLightDismiss: function () { - dialog.hide(DismissalResult.none); - }, - onTakeFocus: function (useSetActive) { - dialog._dismissable.restoreFocus() || - _ElementUtilities._focusFirstFocusableElement(dialog._dom.content) || - _ElementUtilities._tryFocusOnAnyElement(dialog._dom.dialog, useSetActive); - } - }); - this.dialog._dismissedSignal = null; // The signal will be created on demand when show() is called - this.dialog._setState(States.Hidden, false); - }, - exit: _, - show: function ContentDialog_InitState_show() { - throw "It's illegal to call show on the Init state"; - }, - hide: _, - onCommandClicked: _, - onInputPaneShown: _, - onInputPaneHidden: _ - }), - // A rest state. The dialog is hidden and is waiting for the app to call show. - Hidden: _Base.Class.define(null, { - name: "Hidden", - hidden: true, - enter: function ContentDialog_HiddenState_enter(showIsPending) { - if (showIsPending) { - this.show(); - } - }, - exit: _, - show: function ContentDialog_HiddenState_show() { - var dismissedSignal = this.dialog._dismissedSignal = new _Signal(); // save the signal in case it changes when switching states - this.dialog._setState(States.BeforeShow); - return dismissedSignal.promise; - }, - hide: _, - onCommandClicked: _, - onInputPaneShown: _, - onInputPaneHidden: _ - }), - // An event state. The dialog fires the beforeshow event. - BeforeShow: _Base.Class.define(null, { - name: "BeforeShow", - hidden: true, - enter: function ContentDialog_BeforeShowState_enter() { - interruptible(this, function (that, ready) { - return ready.then(function () { - return that.dialog._fireBeforeShow(); // Give opportunity for chain to be canceled when calling into app code - }).then(function (shouldShow) { - if (!shouldShow) { - that.dialog._cancelDismissalPromise(null); // Give opportunity for chain to be canceled when calling into app code - } - return shouldShow; - }).then(function (shouldShow) { - if (shouldShow) { - that.dialog._setState(States.Showing); - } else { - that.dialog._setState(States.Hidden, false); - } - }); - }); - }, - exit: cancelInterruptibles, - show: function ContentDialog_BeforeShowState_show() { - return Promise.wrapError(new _ErrorFromName("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing", Strings.contentDialogAlreadyShowing)); - }, - hide: _, - onCommandClicked: _, - onInputPaneShown: _, - onInputPaneHidden: _ - }), - // An animation/event state. The dialog plays its entrance animation and fires aftershow. - Showing: _Base.Class.define(null, { - name: "Showing", - hidden: { - get: function ContentDialog_ShowingState_hidden_get() { - return !!this._pendingHide; - } - }, - enter: function ContentDialog_ShowingState_enter() { - interruptible(this, function (that, ready) { - return ready.then(function () { - that._pendingHide = null; - _ElementUtilities.addClass(that.dialog._dom.root, ClassNames._visible); - that.dialog._addExternalListeners(); - if (_WinRT.Windows.UI.ViewManagement.InputPane) { - var inputPaneHeight = _WinRT.Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height; - if (inputPaneHeight > 0) { - that.dialog._renderForInputPane(inputPaneHeight); - } - } - _LightDismissService.shown(that.dialog._dismissable); - return that.dialog._playEntranceAnimation(); - }).then(function () { - that.dialog._fireEvent(EventNames.afterShow); // Give opportunity for chain to be canceled when calling into app code - }).then(function () { - that.dialog._setState(States.Shown, that._pendingHide); - }); - }); - }, - exit: cancelInterruptibles, - show: function ContentDialog_ShowingState_show() { - if (this._pendingHide) { - var dismissalResult = this._pendingHide.dismissalResult; - this._pendingHide = null; - return this.dialog._resetDismissalPromise(dismissalResult, new _Signal()).promise; - } else { - return Promise.wrapError(new _ErrorFromName("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing", Strings.contentDialogAlreadyShowing)); - } - }, - hide: function ContentDialog_ShowingState_hide(dismissalResult) { - this._pendingHide = { dismissalResult: dismissalResult }; - }, - onCommandClicked: _, - onInputPaneShown: onInputPaneShown, - onInputPaneHidden: onInputPaneHidden - }), - // A rest state. The dialog is shown and is waiting for the user or the app to trigger hide. - Shown: _Base.Class.define(null, { - name: "Shown", - hidden: false, - enter: function ContentDialog_ShownState_enter(pendingHide) { - if (pendingHide) { - this.hide(pendingHide.dismissalResult); - } - }, - exit: _, - show: function ContentDialog_ShownState_show() { - return Promise.wrapError(new _ErrorFromName("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing", Strings.contentDialogAlreadyShowing)); - }, - hide: function ContentDialog_ShownState_hide(dismissalResult) { - this.dialog._setState(States.BeforeHide, dismissalResult); - }, - onCommandClicked: function ContentDialog_ShownState_onCommandClicked(dismissalResult) { - this.hide(dismissalResult); - }, - onInputPaneShown: onInputPaneShown, - onInputPaneHidden: onInputPaneHidden - }), - // An event state. The dialog fires the beforehide event. - BeforeHide: _Base.Class.define(null, { - name: "BeforeHide", - hidden: false, - enter: function ContentDialog_BeforeHideState_enter(dismissalResult) { - interruptible(this, function (that, ready) { - return ready.then(function () { - return that.dialog._fireBeforeHide(dismissalResult); // Give opportunity for chain to be canceled when calling into app code - }).then(function (shouldHide) { - if (shouldHide) { - that.dialog._setState(States.Hiding, dismissalResult); - } else { - that.dialog._setState(States.Shown, null); - } - }); - }); - }, - exit: cancelInterruptibles, - show: function ContentDialog_BeforeHideState_show() { - return Promise.wrapError(new _ErrorFromName("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing", Strings.contentDialogAlreadyShowing)); - }, - hide: _, - onCommandClicked: _, - onInputPaneShown: onInputPaneShown, - onInputPaneHidden: onInputPaneHidden - }), - // An animation/event state. The dialog plays the exit animation and fires the afterhide event. - Hiding: _Base.Class.define(null, { - name: "Hiding", - hidden: { - get: function ContentDialog_HidingState_hidden_get() { - return !this._showIsPending; - } - }, - enter: function ContentDialog_HidingState_enter(dismissalResult) { - interruptible(this, function (that, ready) { - return ready.then(function () { - that._showIsPending = false; - that.dialog._resetDismissalPromise(dismissalResult, null); // Give opportunity for chain to be canceled when calling into app code - }).then(function () { - return that.dialog._playExitAnimation(); - }).then(function () { - that.dialog._removeExternalListeners(); - _LightDismissService.hidden(that.dialog._dismissable); - _ElementUtilities.removeClass(that.dialog._dom.root, ClassNames._visible); - that.dialog._clearInputPaneRendering(); - that.dialog._fireAfterHide(dismissalResult); // Give opportunity for chain to be canceled when calling into app code - }).then(function () { - that.dialog._setState(States.Hidden, that._showIsPending); - }); - }); - }, - exit: cancelInterruptibles, - show: function ContentDialog_HidingState_show() { - if (this._showIsPending) { - return Promise.wrapError(new _ErrorFromName("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing", Strings.contentDialogAlreadyShowing)); - } else { - this._showIsPending = true; - this.dialog._dismissedSignal = new _Signal(); - return this.dialog._dismissedSignal.promise; - } - }, - hide: function ContentDialog_HidingState_hide(dismissalResult) { - if (this._showIsPending) { - this._showIsPending = false; - this.dialog._resetDismissalPromise(dismissalResult, null); - } - }, - onCommandClicked: _, - onInputPaneShown: _, - onInputPaneHidden: _ - }), - Disposed: _Base.Class.define(null, { - name: "Disposed", - hidden: true, - enter: function ContentDialog_DisposedState_enter() { - _LightDismissService.hidden(this.dialog._dismissable); - this.dialog._removeExternalListeners(); - if (this.dialog._dismissedSignal) { - this.dialog._dismissedSignal.error(new _ErrorFromName("WinJS.UI.ContentDialog.ControlDisposed", Strings.controlDisposed)); - } - }, - exit: _, - show: function ContentDialog_DisposedState_show() { - return Promise.wrapError(new _ErrorFromName("WinJS.UI.ContentDialog.ControlDisposed", Strings.controlDisposed)); - }, - hide: _, - onCommandClicked: _, - onInputPaneShown: _, - onInputPaneHidden: _ - }), - }; - - var ContentDialog = _Base.Class.define(function ContentDialog_ctor(element, options) { - /// - /// - /// Creates a new ContentDialog control. - /// - /// - /// The DOM element that hosts the ContentDialog control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". For example, to provide a handler for the beforehide event, - /// add a property named "onbeforehide" to the options object and set its value to the event handler. - /// - /// - /// The new ContentDialog. - /// - /// - - // Check to make sure we weren't duplicated - if (element && element.winControl) { - throw new _ErrorFromName("WinJS.UI.ContentDialog.DuplicateConstruction", Strings.duplicateConstruction); - } - options = options || {}; - - this._onInputPaneShownBound = this._onInputPaneShown.bind(this); - this._onInputPaneHiddenBound = this._onInputPaneHidden.bind(this); - - this._disposed = false; - this._resizedForInputPane = false; - this._currentFocus = null; - - this._initializeDom(element || _Global.document.createElement("div")); - this._setState(States.Init); - - this.title = ""; - this.primaryCommandText = ""; - this.primaryCommandDisabled = false; - this.secondaryCommandText = ""; - this.secondaryCommandDisabled = false; - - _Control.setOptions(this, options); - }, { - /// - element: { - get: function ContentDialog_element_get() { - return this._dom.root; - } - }, - - /// - /// The text displayed as the title of the dialog. - /// - title: { - get: function ContentDialog_title_get() { - return this._title; - }, - set: function ContentDialog_title_set(value) { - value = value || ""; - if (this._title !== value) { - this._title = value; - this._dom.title.textContent = value; - this._dom.title.style.display = value ? "" : "none"; - } - } - }, - - /// - /// The text displayed on the primary command's button. - /// - primaryCommandText: { - get: function ContentDialog_primaryCommandText_get() { - return this._primaryCommandText; - }, - set: function ContentDialog_primaryCommandText_set(value) { - value = value || ""; - if (this._primaryCommandText !== value) { - this._primaryCommandText = value; - this._dom.commands[0].textContent = value; - this._updateCommandsUI(); - } - } - }, - - /// - /// The text displayed on the secondary command's button. - /// - secondaryCommandText: { - get: function ContentDialog_secondaryCommandText_get() { - return this._secondaryCommandText; - }, - set: function ContentDialog_secondaryCommandText_set(value) { - value = value || ""; - if (this._secondaryCommandText !== value) { - this._secondaryCommandText = value; - this._dom.commands[1].textContent = value; - this._updateCommandsUI(); - } - } - }, - - /// - /// Indicates whether the button representing the primary command is currently disabled. - /// - primaryCommandDisabled: { - get: function ContentDialog_primaryCommandDisabled_get() { - return this._primaryCommandDisabled; - }, - set: function ContentDialog_primaryCommandDisabled_set(value) { - value = !!value; - if (this._primaryCommandDisabled !== value) { - this._primaryCommandDisabled = value; - this._dom.commands[0].disabled = value; - } - } - }, - - /// - /// Indicates whether the button representing the secondary command is currently disabled. - /// - secondaryCommandDisabled: { - get: function ContentDialog_secondaryCommandDisabled_get() { - return this._secondaryCommandDisabled; - }, - set: function ContentDialog_secondaryCommandDisabled_set(value) { - value = !!value; - if (this._secondaryCommandDisabled !== value) { - this._secondaryCommandDisabled = value; - this._dom.commands[1].disabled = value; - } - } - }, - - /// - hidden: { - get: function ContentDialog_hidden_get() { - return this._state.hidden; - }, - set: function ContentDialog_hidden_set(hidden) { - if (!hidden && this._state.hidden) { - var nop = function () { - }; - // Show returns a promise. If hidden is set while the ContentDialog is disposed, show will return a promise - // error which will be impossible to handle and it'll cause the app to terminate. We'll eat the promise returned by show - // to stop that from happening. - this.show().done(nop, nop); - } else if (hidden && !this._state.hidden) { - this.hide(DismissalResult.none); - } - } - }, - - dispose: function ContentDialog_dispose() { - /// - /// - /// Disposes this control. - /// - /// - if (this._disposed) { - return; - } - this._setState(States.Disposed); - this._disposed = true; - _Dispose._disposeElement(this._dom.content); - }, - - show: function ContentDialog_show() { - /// - /// - /// Shows the ContentDialog. Only one ContentDialog may be shown at a time. If another - /// ContentDialog is already shown, this ContentDialog will remain hidden. - /// - /// - /// A promise which is successfully fulfilled when the dialog is dismissed. The - /// completion value indicates the dialog's dismissal result. This may - /// be 'primary', 'secondary', 'none', or whatever custom value was passed to hide. - /// If this ContentDialog cannot be shown because a ContentDialog is already showing - /// or the ContentDialog is disposed, then the return value is a promise which is in - /// an error state. If preventDefault() is called on the beforeshow event, then this - /// promise will be canceled. - /// - /// - return this._state.show(); - }, - - hide: function ContentDialog_hide(result) { - /// - /// - /// Hides the ContentDialog. - /// - /// - /// A value indicating why the dialog is being hidden. The promise returned - /// by show will be fulfilled with this value. - /// - /// - this._state.hide(result === undefined ? DismissalResult.none : result); - }, - - _initializeDom: function ContentDialog_initializeDom(root) { - // Reparent the children of the root element into the content element. - var contentEl = _Global.document.createElement("div"); - contentEl.className = ClassNames.content; - _ElementUtilities._reparentChildren(root, contentEl); - - root.winControl = this; - _ElementUtilities.addClass(root, ClassNames.contentDialog); - _ElementUtilities.addClass(root, ClassNames._verticalAlignment); - _ElementUtilities.addClass(root, "win-disposable"); - root.innerHTML = - '
' + - '
' + - '' + - '
' + - '
'; - - var dom = {}; - dom.root = root; - dom.backgroundOverlay = dom.root.firstElementChild; - dom.startBodyTab = dom.backgroundOverlay.nextElementSibling; - dom.dialog = dom.startBodyTab.nextElementSibling; - dom.title = dom.dialog.firstElementChild; - dom.scroller = dom.title.nextElementSibling; - dom.commandContainer = dom.scroller.nextElementSibling; - dom.commandSpacer = dom.commandContainer.firstElementChild; - dom.commands = []; - dom.commands.push(dom.commandSpacer.nextElementSibling); - dom.commands.push(dom.commands[0].nextElementSibling); - dom.endBodyTab = dom.dialog.nextElementSibling; - dom.content = contentEl; - this._dom = dom; - - // Put the developer's content into the scroller - dom.scroller.appendChild(dom.content); - - _ElementUtilities._ensureId(dom.title); - _ElementUtilities._ensureId(dom.startBodyTab); - _ElementUtilities._ensureId(dom.endBodyTab); - dom.dialog.setAttribute("aria-labelledby", dom.title.id); - dom.startBodyTab.setAttribute("x-ms-aria-flowfrom", dom.endBodyTab.id); - dom.endBodyTab.setAttribute("aria-flowto", dom.startBodyTab.id); - this._updateTabIndices(); - - dom.root.addEventListener("keydown", this._onKeyDownEnteringElement.bind(this), true); - _ElementUtilities._addEventListener(dom.root, "pointerdown", this._onPointerDown.bind(this)); - _ElementUtilities._addEventListener(dom.root, "pointerup", this._onPointerUp.bind(this)); - dom.root.addEventListener("click", this._onClick.bind(this)); - _ElementUtilities._addEventListener(dom.startBodyTab, "focusin", this._onStartBodyTabFocusIn.bind(this)); - _ElementUtilities._addEventListener(dom.endBodyTab, "focusin", this._onEndBodyTabFocusIn.bind(this)); - dom.commands[0].addEventListener("click", this._onCommandClicked.bind(this, DismissalResult.primary)); - dom.commands[1].addEventListener("click", this._onCommandClicked.bind(this, DismissalResult.secondary)); - }, - - _updateCommandsUI: function ContentDialog_updateCommandsUI() { - this._dom.commands[0].style.display = this.primaryCommandText ? "" : "none"; - this._dom.commands[1].style.display = this.secondaryCommandText ? "" : "none"; - - // commandSpacer's purpose is to ensure that when only 1 button is shown, that button takes up half - // the width of the dialog and is right-aligned. It works by: - // - When only one command is shown: - // - Coming before the other command in the DOM (so the other command will look right-aligned) - // - Having the same flex-grow as the other command (so it occupies half of the space) - // - Having visibility: hidden (so it's invisible but it takes up space) - // - When both commands are shown: - // - Having display: none (so it doesn't occupy any space and the two shown commands each take up half the dialog) - // - When 0 commands are shown: - // - Having display: none (so the commands area takes up no space) - this._dom.commandSpacer.style.display = this.primaryCommandText && !this.secondaryCommandText || !this.primaryCommandText && this.secondaryCommandText ? "" : "none"; - }, - - // _updateTabIndices and _updateTabIndicesImpl are used in tests - _updateTabIndices: function ContentDialog_updateTabIndices() { - if (!this._updateTabIndicesThrottled) { - this._updateTabIndicesThrottled = _BaseUtils._throttledFunction(100, this._updateTabIndicesImpl.bind(this)); - } - this._updateTabIndicesThrottled(); - }, - _updateTabIndicesImpl: function ContentDialog_updateTabIndicesImpl() { - var tabIndex = _ElementUtilities._getHighAndLowTabIndices(this._dom.content); - this._dom.startBodyTab.tabIndex = tabIndex.lowest; - this._dom.commands[0].tabIndex = tabIndex.highest; - this._dom.commands[1].tabIndex = tabIndex.highest; - this._dom.endBodyTab.tabIndex = tabIndex.highest; - }, - - _elementInDialog: function ContentDialog_elementInDialog(element) { - return this._dom.dialog.contains(element) || element === this._dom.startBodyTab || element === this._dom.endBodyTab; - }, - - _onCommandClicked: function ContentDialog_onCommandClicked(dismissalResult) { - this._state.onCommandClicked(dismissalResult); - }, - - _onPointerDown: function ContentDialog_onPointerDown(eventObject) { - eventObject.stopPropagation(); - if (!this._elementInDialog(eventObject.target)) { - eventObject.preventDefault(); - } - }, - - _onPointerUp: function ContentDialog_onPointerUp(eventObject) { - eventObject.stopPropagation(); - if (!this._elementInDialog(eventObject.target)) { - eventObject.preventDefault(); - } - }, - - _onClick: function ContentDialog_onClick(eventObject) { - eventObject.stopPropagation(); - if (!this._elementInDialog(eventObject.target)) { - eventObject.preventDefault(); - } - }, - - _onKeyDownEnteringElement: function ContentDialog_onKeyDownEnteringElement(eventObject) { - if (eventObject.keyCode === _ElementUtilities.Key.tab) { - this._updateTabIndices(); - } - }, - - _onStartBodyTabFocusIn: function ContentDialog_onStartBodyTabFocusIn() { - _ElementUtilities._focusLastFocusableElement(this._dom.dialog); - }, - - _onEndBodyTabFocusIn: function ContentDialog_onEndBodyTabFocusIn() { - _ElementUtilities._focusFirstFocusableElement(this._dom.dialog); - }, - - _onInputPaneShown: function ContentDialog_onInputPaneShown(eventObject) { - this._state.onInputPaneShown(eventObject.detail.originalEvent); - }, - - _onInputPaneHidden: function ContentDialog_onInputPaneHidden() { - this._state.onInputPaneHidden(); - }, - - // - // Methods called by states - // - - _setState: function ContentDialog_setState(NewState, arg0) { - if (!this._disposed) { - this._state && this._state.exit(); - this._state = new NewState(); - this._state.dialog = this; - this._state.enter(arg0); - } - }, - - // Calls into arbitrary app code - _resetDismissalPromise: function ContentDialog_resetDismissalPromise(dismissalResult, newSignal) { - var dismissedSignal = this._dismissedSignal; - var newDismissedSignal = this._dismissedSignal = newSignal; - dismissedSignal.complete({ result: dismissalResult }); - return newDismissedSignal; - }, - - // Calls into arbitrary app code - _cancelDismissalPromise: function ContentDialog_cancelDismissalPromise(newSignal) { - var dismissedSignal = this._dismissedSignal; - var newDismissedSignal = this._dismissedSignal = newSignal; - dismissedSignal.cancel(); - return newDismissedSignal; - }, - - // Calls into arbitrary app code - _fireEvent: function ContentDialog_fireEvent(eventName, options) { - options = options || {}; - var detail = options.detail || null; - var cancelable = !!options.cancelable; - - var eventObject = _Global.document.createEvent("CustomEvent"); - eventObject.initCustomEvent(eventName, true, cancelable, detail); - return this._dom.root.dispatchEvent(eventObject); - }, - - // Calls into arbitrary app code - _fireBeforeShow: function ContentDialog_fireBeforeShow() { - return this._fireEvent(EventNames.beforeShow, { - cancelable: true - }); - }, - - // Calls into arbitrary app code - _fireBeforeHide: function ContentDialog_fireBeforeHide(dismissalResult) { - return this._fireEvent(EventNames.beforeHide, { - detail: { result: dismissalResult }, - cancelable: true - }); - }, - - // Calls into arbitrary app code - _fireAfterHide: function ContentDialog_fireAfterHide(dismissalResult) { - this._fireEvent(EventNames.afterHide, { - detail: { result: dismissalResult } - }); - }, - - _playEntranceAnimation: function ContentDialog_playEntranceAnimation() { - return cancelablePromise(_Animations.fadeIn(this._dom.root)); - }, - - _playExitAnimation: function ContentDialog_playExitAnimation() { - return cancelablePromise(_Animations.fadeOut(this._dom.root)); - }, - - _addExternalListeners: function ContentDialog_addExternalListeners() { - _ElementUtilities._inputPaneListener.addEventListener(this._dom.root, "showing", this._onInputPaneShownBound); - _ElementUtilities._inputPaneListener.addEventListener(this._dom.root, "hiding", this._onInputPaneShownBound); - }, - - _removeExternalListeners: function ContentDialog_removeExternalListeners() { - _ElementUtilities._inputPaneListener.removeEventListener(this._dom.root, "showing", this._onInputPaneShownBound); - _ElementUtilities._inputPaneListener.removeEventListener(this._dom.root, "hiding", this._onInputPaneShownBound); - }, - - _renderForInputPane: function ContentDialog_renderForInputPane(inputPaneHeight) { - this._clearInputPaneRendering(); - - var dialog = this._dom.dialog; - var style = dialog.style; - var left = dialog.offsetLeft; - var top = dialog.offsetTop; - var height = dialog.offsetHeight; - var bottom = top + height; - var visibleBottom = this._dom.root.offsetHeight - inputPaneHeight; - var titleHeight = _ElementUtilities.getTotalHeight(this._dom.title); - var commandsHeight = _ElementUtilities.getTotalHeight(this._dom.commandContainer); - - if (bottom > visibleBottom) { - var newHeight = height - (bottom - visibleBottom); - if (newHeight - titleHeight - commandsHeight < minContentHeightWithInputPane) { - // Put title into scroller so there's more screen real estate for the content - this._dom.scroller.insertBefore(this._dom.title, this._dom.content); - } - - this._dom.root.style.display = "block"; - style.height = newHeight + "px"; - style.position = "absolute"; - style.left = left + "px"; - style.top = top + "px"; - style.minHeight = 0; - - this._resizedForInputPane = true; - _Global.document.activeElement.focus(); // Ensure activeElement is scrolled into view - } - }, - - _clearInputPaneRendering: function ContentDialog_clearInputPaneRendering() { - if (this._resizedForInputPane) { - if (this._dom.title.parentNode !== this._dom.dialog) { - // Make sure the title isn't in the scroller - this._dom.dialog.insertBefore(this._dom.title, this._dom.scroller); - } - - var style = this._dom.dialog.style; - this._dom.root.style.display = ""; - style.height = ""; - style.position = ""; - style.left = ""; - style.top = ""; - style.minHeight = ""; - this._resizedForInputPane = false; - } - } - }, { - /// - /// Specifies the result of dismissing the ContentDialog. - /// - DismissalResult: DismissalResult, - - _ClassNames: ClassNames - }); - _Base.Class.mix(ContentDialog, _Events.createEventProperties( - "beforeshow", - "aftershow", - "beforehide", - "afterhide" - )); - _Base.Class.mix(ContentDialog, _Control.DOMEventMixin); - return ContentDialog; - }) - }); -}); - - -define('require-style!less/styles-splitview',[],function(){}); - -define('require-style!less/colors-splitview',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/SplitView/_SplitView',["require", "exports", '../../Animations', '../../Core/_Base', '../../Core/_BaseUtils', '../../Utilities/_Control', '../../Utilities/_Dispose', '../../Utilities/_ElementUtilities', '../../Core/_ErrorFromName', '../../Core/_Events', '../../Core/_Global', '../../_LightDismissService', '../../Utilities/_OpenCloseMachine'], function (require, exports, Animations, _Base, _BaseUtils, _Control, _Dispose, _ElementUtilities, _ErrorFromName, _Events, _Global, _LightDismissService, _OpenCloseMachine) { - require(["require-style!less/styles-splitview"]); - require(["require-style!less/colors-splitview"]); - "use strict"; - var transformNames = _BaseUtils._browserStyleEquivalents["transform"]; - var Strings = { - get duplicateConstruction() { - return "Invalid argument: Controls may only be instantiated one time for each DOM element"; - } - }; - var ClassNames = { - splitView: "win-splitview", - pane: "win-splitview-pane", - content: "win-splitview-content", - // closed/opened - paneClosed: "win-splitview-pane-closed", - paneOpened: "win-splitview-pane-opened", - _panePlaceholder: "win-splitview-paneplaceholder", - _paneWrapper: "win-splitview-panewrapper", - _contentWrapper: "win-splitview-contentwrapper", - // placement - _placementLeft: "win-splitview-placementleft", - _placementRight: "win-splitview-placementright", - _placementTop: "win-splitview-placementtop", - _placementBottom: "win-splitview-placementbottom", - // closed display mode - _closedDisplayNone: "win-splitview-closeddisplaynone", - _closedDisplayInline: "win-splitview-closeddisplayinline", - // opened display mode - _openedDisplayInline: "win-splitview-openeddisplayinline", - _openedDisplayOverlay: "win-splitview-openeddisplayoverlay" - }; - var EventNames = { - beforeOpen: "beforeopen", - afterOpen: "afteropen", - beforeClose: "beforeclose", - afterClose: "afterclose" - }; - var Dimension = { - width: "width", - height: "height" - }; - var ClosedDisplayMode = { - /// - /// When the pane is closed, it is not visible and doesn't take up any space. - /// - none: "none", - /// - /// When the pane is closed, it occupies space leaving less room for the SplitView's content. - /// - inline: "inline" - }; - var OpenedDisplayMode = { - /// - /// When the pane is open, it occupies space leaving less room for the SplitView's content. - /// - inline: "inline", - /// - /// When the pane is open, it doesn't take up any space and it is light dismissable. - /// - overlay: "overlay" - }; - var PanePlacement = { - /// - /// Pane is positioned left of the SplitView's content. - /// - left: "left", - /// - /// Pane is positioned right of the SplitView's content. - /// - right: "right", - /// - /// Pane is positioned above the SplitView's content. - /// - top: "top", - /// - /// Pane is positioned below the SplitView's content. - /// - bottom: "bottom" - }; - var closedDisplayModeClassMap = {}; - closedDisplayModeClassMap[ClosedDisplayMode.none] = ClassNames._closedDisplayNone; - closedDisplayModeClassMap[ClosedDisplayMode.inline] = ClassNames._closedDisplayInline; - var openedDisplayModeClassMap = {}; - openedDisplayModeClassMap[OpenedDisplayMode.overlay] = ClassNames._openedDisplayOverlay; - openedDisplayModeClassMap[OpenedDisplayMode.inline] = ClassNames._openedDisplayInline; - var panePlacementClassMap = {}; - panePlacementClassMap[PanePlacement.left] = ClassNames._placementLeft; - panePlacementClassMap[PanePlacement.right] = ClassNames._placementRight; - panePlacementClassMap[PanePlacement.top] = ClassNames._placementTop; - panePlacementClassMap[PanePlacement.bottom] = ClassNames._placementBottom; - // Versions of add/removeClass that are no ops when called with falsy class names. - function addClass(element, className) { - className && _ElementUtilities.addClass(element, className); - } - function removeClass(element, className) { - className && _ElementUtilities.removeClass(element, className); - } - function rectToThickness(rect, dimension) { - return (dimension === Dimension.width) ? { - content: rect.contentWidth, - total: rect.totalWidth - } : { - content: rect.contentHeight, - total: rect.totalHeight - }; - } - /// - /// - /// Displays a SplitView which renders a collapsable pane next to arbitrary HTML content. - /// - /// - /// - /// - /// ]]> - /// Raised just before opening the pane. Call preventDefault on this event to stop the pane from opening. - /// Raised immediately after the pane is fully opened. - /// Raised just before closing the pane. Call preventDefault on this event to stop the pane from closing. - /// Raised immediately after the pane is fully closed. - /// The entire SplitView control. - /// The element which hosts the SplitView's pane. - /// The element which hosts the SplitView's content. - /// - /// - var SplitView = (function () { - function SplitView(element, options) { - /// - /// - /// Creates a new SplitView control. - /// - /// - /// The DOM element that hosts the SplitView control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". For example, to provide a handler for the beforeclose event, - /// add a property named "onbeforeclose" to the options object and set its value to the event handler. - /// - /// - /// The new SplitView. - /// - /// - var _this = this; - if (options === void 0) { options = {}; } - // State private to _updateDomImpl. No other method should make use of it. - // - // Nothing has been rendered yet so these are all initialized to undefined. Because - // they are undefined, the first time _updateDomImpl is called, they will all be - // rendered. - this._updateDomImpl_rendered = { - paneIsFirst: undefined, - isOpenedMode: undefined, - closedDisplayMode: undefined, - openedDisplayMode: undefined, - panePlacement: undefined, - panePlaceholderWidth: undefined, - panePlaceholderHeight: undefined, - isOverlayShown: undefined - }; - // Check to make sure we weren't duplicated - if (element && element["winControl"]) { - throw new _ErrorFromName("WinJS.UI.SplitView.DuplicateConstruction", Strings.duplicateConstruction); - } - this._initializeDom(element || _Global.document.createElement("div")); - this._machine = new _OpenCloseMachine.OpenCloseMachine({ - eventElement: this._dom.root, - onOpen: function () { - _this._cachedHiddenPaneThickness = null; - var hiddenPaneThickness = _this._getHiddenPaneThickness(); - _this._isOpenedMode = true; - _this._updateDomImpl(); - return _this._playShowAnimation(hiddenPaneThickness); - }, - onClose: function () { - return _this._playHideAnimation(_this._getHiddenPaneThickness()).then(function () { - _this._isOpenedMode = false; - _this._updateDomImpl(); - }); - }, - onUpdateDom: function () { - _this._updateDomImpl(); - }, - onUpdateDomWithIsOpened: function (isOpened) { - _this._isOpenedMode = isOpened; - _this._updateDomImpl(); - } - }); - // Initialize private state. - this._disposed = false; - this._dismissable = new _LightDismissService.LightDismissableElement({ - element: this._dom.paneWrapper, - tabIndex: -1, - onLightDismiss: function () { - _this.closePane(); - }, - onTakeFocus: function (useSetActive) { - _this._dismissable.restoreFocus() || _ElementUtilities._tryFocusOnAnyElement(_this._dom.pane, useSetActive); - } - }); - this._cachedHiddenPaneThickness = null; - // Initialize public properties. - this.paneOpened = false; - this.closedDisplayMode = ClosedDisplayMode.inline; - this.openedDisplayMode = OpenedDisplayMode.overlay; - this.panePlacement = PanePlacement.left; - _Control.setOptions(this, options); - // Exit the Init state. - _ElementUtilities._inDom(this._dom.root).then(function () { - _this._rtl = _Global.getComputedStyle(_this._dom.root).direction === 'rtl'; - _this._machine.exitInit(); - }); - } - Object.defineProperty(SplitView.prototype, "element", { - /// - get: function () { - return this._dom.root; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitView.prototype, "paneElement", { - /// - get: function () { - return this._dom.pane; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitView.prototype, "contentElement", { - /// - get: function () { - return this._dom.content; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitView.prototype, "closedDisplayMode", { - /// - /// Gets or sets the display mode of the SplitView's pane when it is hidden. - /// - get: function () { - return this._closedDisplayMode; - }, - set: function (value) { - if (ClosedDisplayMode[value] && this._closedDisplayMode !== value) { - this._closedDisplayMode = value; - this._cachedHiddenPaneThickness = null; - this._machine.updateDom(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitView.prototype, "openedDisplayMode", { - /// - /// Gets or sets the display mode of the SplitView's pane when it is open. - /// - get: function () { - return this._openedDisplayMode; - }, - set: function (value) { - if (OpenedDisplayMode[value] && this._openedDisplayMode !== value) { - this._openedDisplayMode = value; - this._cachedHiddenPaneThickness = null; - this._machine.updateDom(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitView.prototype, "panePlacement", { - /// - /// Gets or sets the placement of the SplitView's pane. - /// - get: function () { - return this._panePlacement; - }, - set: function (value) { - if (PanePlacement[value] && this._panePlacement !== value) { - this._panePlacement = value; - this._cachedHiddenPaneThickness = null; - this._machine.updateDom(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitView.prototype, "paneOpened", { - /// - get: function () { - return this._machine.opened; - }, - set: function (value) { - this._machine.opened = value; - }, - enumerable: true, - configurable: true - }); - SplitView.prototype.dispose = function () { - /// - /// - /// Disposes this control. - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - this._machine.dispose(); - _LightDismissService.hidden(this._dismissable); - _Dispose._disposeElement(this._dom.pane); - _Dispose._disposeElement(this._dom.content); - }; - SplitView.prototype.openPane = function () { - /// - /// - /// Opens the SplitView's pane. - /// - /// - this._machine.open(); - }; - SplitView.prototype.closePane = function () { - /// - /// - /// Closes the SplitView's pane. - /// - /// - this._machine.close(); - }; - SplitView.prototype._initializeDom = function (root) { - // The first child is the pane - var paneEl = root.firstElementChild || _Global.document.createElement("div"); - _ElementUtilities.addClass(paneEl, ClassNames.pane); - if (!paneEl.hasAttribute("tabIndex")) { - paneEl.tabIndex = -1; - } - // All other children are members of the content - var contentEl = _Global.document.createElement("div"); - _ElementUtilities.addClass(contentEl, ClassNames.content); - var child = paneEl.nextSibling; - while (child) { - var sibling = child.nextSibling; - contentEl.appendChild(child); - child = sibling; - } - // paneWrapper's purpose is to clip the pane during the pane resize animation - var paneWrapperEl = _Global.document.createElement("div"); - paneWrapperEl.className = ClassNames._paneWrapper; - paneWrapperEl.appendChild(paneEl); - var panePlaceholderEl = _Global.document.createElement("div"); - panePlaceholderEl.className = ClassNames._panePlaceholder; - // contentWrapper is an extra element we need to allow heights to be specified as percentages (e.g. height: 100%) - // for elements within the content area. It works around this Chrome bug: - // Issue 428049: 100% height doesn't work on child of a definite-flex-basis flex item (in vertical flex container) - // https://code.google.com/p/chromium/issues/detail?id=428049 - // The workaround is that putting a position: absolute element (_dom.content) within the flex item (_dom.contentWrapper) - // allows percentage heights to work within the absolutely positioned element (_dom.content). - var contentWrapperEl = _Global.document.createElement("div"); - contentWrapperEl.className = ClassNames._contentWrapper; - contentWrapperEl.appendChild(contentEl); - root["winControl"] = this; - _ElementUtilities.addClass(root, ClassNames.splitView); - _ElementUtilities.addClass(root, "win-disposable"); - this._dom = { - root: root, - pane: paneEl, - paneWrapper: paneWrapperEl, - panePlaceholder: panePlaceholderEl, - content: contentEl, - contentWrapper: contentWrapperEl - }; - }; - SplitView.prototype._measureElement = function (element) { - var style = getComputedStyle(element); - var position = _ElementUtilities._getPositionRelativeTo(element, this._dom.root); - var marginLeft = parseInt(style.marginLeft, 10); - var marginTop = parseInt(style.marginTop, 10); - return { - left: position.left - marginLeft, - top: position.top - marginTop, - contentWidth: _ElementUtilities.getContentWidth(element), - contentHeight: _ElementUtilities.getContentHeight(element), - totalWidth: _ElementUtilities.getTotalWidth(element), - totalHeight: _ElementUtilities.getTotalHeight(element) - }; - }; - SplitView.prototype._setContentRect = function (contentRect) { - var contentWrapperStyle = this._dom.contentWrapper.style; - contentWrapperStyle.left = contentRect.left + "px"; - contentWrapperStyle.top = contentRect.top + "px"; - contentWrapperStyle.height = contentRect.contentHeight + "px"; - contentWrapperStyle.width = contentRect.contentWidth + "px"; - }; - // Overridden by tests. - SplitView.prototype._prepareAnimation = function (paneRect, contentRect) { - var paneWrapperStyle = this._dom.paneWrapper.style; - paneWrapperStyle.position = "absolute"; - paneWrapperStyle.left = paneRect.left + "px"; - paneWrapperStyle.top = paneRect.top + "px"; - paneWrapperStyle.height = paneRect.totalHeight + "px"; - paneWrapperStyle.width = paneRect.totalWidth + "px"; - var contentWrapperStyle = this._dom.contentWrapper.style; - contentWrapperStyle.position = "absolute"; - this._setContentRect(contentRect); - }; - // Overridden by tests. - SplitView.prototype._clearAnimation = function () { - var paneWrapperStyle = this._dom.paneWrapper.style; - paneWrapperStyle.position = ""; - paneWrapperStyle.left = ""; - paneWrapperStyle.top = ""; - paneWrapperStyle.height = ""; - paneWrapperStyle.width = ""; - paneWrapperStyle[transformNames.scriptName] = ""; - var contentWrapperStyle = this._dom.contentWrapper.style; - contentWrapperStyle.position = ""; - contentWrapperStyle.left = ""; - contentWrapperStyle.top = ""; - contentWrapperStyle.height = ""; - contentWrapperStyle.width = ""; - contentWrapperStyle[transformNames.scriptName] = ""; - var paneStyle = this._dom.pane.style; - paneStyle.height = ""; - paneStyle.width = ""; - paneStyle[transformNames.scriptName] = ""; - }; - SplitView.prototype._getHiddenContentRect = function (shownContentRect, hiddenPaneThickness, shownPaneThickness) { - if (this.openedDisplayMode === OpenedDisplayMode.overlay) { - return shownContentRect; - } - else { - var placementRight = this._rtl ? PanePlacement.left : PanePlacement.right; - var multiplier = this.panePlacement === placementRight || this.panePlacement === PanePlacement.bottom ? 0 : 1; - var paneDiff = { - content: shownPaneThickness.content - hiddenPaneThickness.content, - total: shownPaneThickness.total - hiddenPaneThickness.total - }; - return this._horizontal ? { - left: shownContentRect.left - multiplier * paneDiff.total, - top: shownContentRect.top, - contentWidth: shownContentRect.contentWidth + paneDiff.content, - contentHeight: shownContentRect.contentHeight, - totalWidth: shownContentRect.totalWidth + paneDiff.total, - totalHeight: shownContentRect.totalHeight - } : { - left: shownContentRect.left, - top: shownContentRect.top - multiplier * paneDiff.total, - contentWidth: shownContentRect.contentWidth, - contentHeight: shownContentRect.contentHeight + paneDiff.content, - totalWidth: shownContentRect.totalWidth, - totalHeight: shownContentRect.totalHeight + paneDiff.total - }; - } - }; - Object.defineProperty(SplitView.prototype, "_horizontal", { - get: function () { - return this.panePlacement === PanePlacement.left || this.panePlacement === PanePlacement.right; - }, - enumerable: true, - configurable: true - }); - SplitView.prototype._getHiddenPaneThickness = function () { - if (this._cachedHiddenPaneThickness === null) { - if (this._closedDisplayMode === ClosedDisplayMode.none) { - this._cachedHiddenPaneThickness = { content: 0, total: 0 }; - } - else { - if (this._isOpenedMode) { - _ElementUtilities.removeClass(this._dom.root, ClassNames.paneOpened); - _ElementUtilities.addClass(this._dom.root, ClassNames.paneClosed); - } - var size = this._measureElement(this._dom.pane); - this._cachedHiddenPaneThickness = rectToThickness(size, this._horizontal ? Dimension.width : Dimension.height); - if (this._isOpenedMode) { - _ElementUtilities.removeClass(this._dom.root, ClassNames.paneClosed); - _ElementUtilities.addClass(this._dom.root, ClassNames.paneOpened); - } - } - } - return this._cachedHiddenPaneThickness; - }; - // Should be called while SplitView is rendered in its opened mode - // Overridden by tests. - SplitView.prototype._playShowAnimation = function (hiddenPaneThickness) { - var _this = this; - var dim = this._horizontal ? Dimension.width : Dimension.height; - var shownPaneRect = this._measureElement(this._dom.pane); - var shownContentRect = this._measureElement(this._dom.content); - var shownPaneThickness = rectToThickness(shownPaneRect, dim); - var hiddenContentRect = this._getHiddenContentRect(shownContentRect, hiddenPaneThickness, shownPaneThickness); - this._prepareAnimation(shownPaneRect, hiddenContentRect); - var playPaneAnimation = function () { - var placementRight = _this._rtl ? PanePlacement.left : PanePlacement.right; - // What percentage of the size change should be skipped? (e.g. let's do the first - // 30% of the size change instantly and then animate the other 70%) - var animationOffsetFactor = 0.3; - var from = hiddenPaneThickness.total + animationOffsetFactor * (shownPaneThickness.total - hiddenPaneThickness.total); - return Animations._resizeTransition(_this._dom.paneWrapper, _this._dom.pane, { - from: from, - to: shownPaneThickness.total, - actualSize: shownPaneThickness.total, - dimension: dim, - anchorTrailingEdge: _this.panePlacement === placementRight || _this.panePlacement === PanePlacement.bottom - }); - }; - var playShowAnimation = function () { - if (_this.openedDisplayMode === OpenedDisplayMode.inline) { - _this._setContentRect(shownContentRect); - } - return playPaneAnimation(); - }; - return playShowAnimation().then(function () { - _this._clearAnimation(); - }); - }; - // Should be called while SplitView is rendered in its opened mode - // Overridden by tests. - SplitView.prototype._playHideAnimation = function (hiddenPaneThickness) { - var _this = this; - var dim = this._horizontal ? Dimension.width : Dimension.height; - var shownPaneRect = this._measureElement(this._dom.pane); - var shownContentRect = this._measureElement(this._dom.content); - var shownPaneThickness = rectToThickness(shownPaneRect, dim); - var hiddenContentRect = this._getHiddenContentRect(shownContentRect, hiddenPaneThickness, shownPaneThickness); - this._prepareAnimation(shownPaneRect, shownContentRect); - var playPaneAnimation = function () { - var placementRight = _this._rtl ? PanePlacement.left : PanePlacement.right; - // What percentage of the size change should be skipped? (e.g. let's do the first - // 30% of the size change instantly and then animate the other 70%) - var animationOffsetFactor = 0.3; - var from = shownPaneThickness.total - animationOffsetFactor * (shownPaneThickness.total - hiddenPaneThickness.total); - return Animations._resizeTransition(_this._dom.paneWrapper, _this._dom.pane, { - from: from, - to: hiddenPaneThickness.total, - actualSize: shownPaneThickness.total, - dimension: dim, - anchorTrailingEdge: _this.panePlacement === placementRight || _this.panePlacement === PanePlacement.bottom - }); - }; - var playHideAnimation = function () { - if (_this.openedDisplayMode === OpenedDisplayMode.inline) { - _this._setContentRect(hiddenContentRect); - } - return playPaneAnimation(); - }; - return playHideAnimation().then(function () { - _this._clearAnimation(); - }); - }; - SplitView.prototype._updateDomImpl = function () { - var rendered = this._updateDomImpl_rendered; - var paneShouldBeFirst = this.panePlacement === PanePlacement.left || this.panePlacement === PanePlacement.top; - if (paneShouldBeFirst !== rendered.paneIsFirst) { - // TODO: restore focus - if (paneShouldBeFirst) { - this._dom.root.appendChild(this._dom.panePlaceholder); - this._dom.root.appendChild(this._dom.paneWrapper); - this._dom.root.appendChild(this._dom.contentWrapper); - } - else { - this._dom.root.appendChild(this._dom.contentWrapper); - this._dom.root.appendChild(this._dom.paneWrapper); - this._dom.root.appendChild(this._dom.panePlaceholder); - } - } - rendered.paneIsFirst = paneShouldBeFirst; - if (rendered.isOpenedMode !== this._isOpenedMode) { - if (this._isOpenedMode) { - _ElementUtilities.removeClass(this._dom.root, ClassNames.paneClosed); - _ElementUtilities.addClass(this._dom.root, ClassNames.paneOpened); - } - else { - _ElementUtilities.removeClass(this._dom.root, ClassNames.paneOpened); - _ElementUtilities.addClass(this._dom.root, ClassNames.paneClosed); - } - } - rendered.isOpenedMode = this._isOpenedMode; - if (rendered.panePlacement !== this.panePlacement) { - removeClass(this._dom.root, panePlacementClassMap[rendered.panePlacement]); - addClass(this._dom.root, panePlacementClassMap[this.panePlacement]); - rendered.panePlacement = this.panePlacement; - } - if (rendered.closedDisplayMode !== this.closedDisplayMode) { - removeClass(this._dom.root, closedDisplayModeClassMap[rendered.closedDisplayMode]); - addClass(this._dom.root, closedDisplayModeClassMap[this.closedDisplayMode]); - rendered.closedDisplayMode = this.closedDisplayMode; - } - if (rendered.openedDisplayMode !== this.openedDisplayMode) { - removeClass(this._dom.root, openedDisplayModeClassMap[rendered.openedDisplayMode]); - addClass(this._dom.root, openedDisplayModeClassMap[this.openedDisplayMode]); - rendered.openedDisplayMode = this.openedDisplayMode; - } - var isOverlayShown = this._isOpenedMode && this.openedDisplayMode === OpenedDisplayMode.overlay; - // panePlaceholder's purpose is to take up the amount of space occupied by the - // hidden pane while the pane is shown in overlay mode. Without this, the content - // would shift as the pane shows and hides in overlay mode. - var width, height; - if (isOverlayShown) { - var hiddenPaneThickness = this._getHiddenPaneThickness(); - if (this._horizontal) { - width = hiddenPaneThickness.total + "px"; - height = ""; - } - else { - width = ""; - height = hiddenPaneThickness.total + "px"; - } - } - else { - width = ""; - height = ""; - } - if (rendered.panePlaceholderWidth !== width || rendered.panePlaceholderHeight !== height) { - var style = this._dom.panePlaceholder.style; - style.width = width; - style.height = height; - rendered.panePlaceholderWidth = width; - rendered.panePlaceholderHeight = height; - } - if (rendered.isOverlayShown !== isOverlayShown) { - if (isOverlayShown) { - _LightDismissService.shown(this._dismissable); - } - else { - _LightDismissService.hidden(this._dismissable); - } - rendered.isOverlayShown = isOverlayShown; - } - }; - /// - /// Display options for a SplitView's pane when it is closed. - /// - SplitView.ClosedDisplayMode = ClosedDisplayMode; - /// - /// Display options for a SplitView's pane when it is open. - /// - SplitView.OpenedDisplayMode = OpenedDisplayMode; - /// - /// Placement options for a SplitView's pane. - /// - SplitView.PanePlacement = PanePlacement; - SplitView.supportedForProcessing = true; - SplitView._ClassNames = ClassNames; - return SplitView; - })(); - exports.SplitView = SplitView; - _Base.Class.mix(SplitView, _Events.createEventProperties(EventNames.beforeOpen, EventNames.afterOpen, EventNames.beforeClose, EventNames.afterClose)); - _Base.Class.mix(SplitView, _Control.DOMEventMixin); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/SplitView',["require", "exports", '../Core/_Base'], function (require, exports, _Base) { - var module = null; - _Base.Namespace.define("WinJS.UI", { - SplitView: { - get: function () { - if (!module) { - require(["./SplitView/_SplitView"], function (m) { - module = m; - }); - } - return module.SplitView; - } - } - }); -}); - - -define('require-style!less/styles-splitviewpanetoggle',[],function(){}); - -define('require-style!less/colors-splitviewpanetoggle',[],function(){}); -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/SplitViewPaneToggle/_SplitViewPaneToggle',["require", "exports", '../../Core/_Base', '../../Utilities/_Control', '../../Utilities/_ElementUtilities', '../../Core/_ErrorFromName', '../../Core/_Events', '../../Core/_Global', '../../Utilities/_KeyboardBehavior', '../../Utilities/_Hoverable'], function (require, exports, _Base, _Control, _ElementUtilities, _ErrorFromName, _Events, _Global, _KeyboardBehavior, _Hoverable) { - _Hoverable.isHoverable; // Force dependency on the hoverable module - require(["require-style!less/styles-splitviewpanetoggle"]); - require(["require-style!less/colors-splitviewpanetoggle"]); - "use strict"; - // This control has 2 modes depending on whether or not the app has provided a SplitView: - // - SplitView not provided - // SplitViewPaneToggle provides button visuals and fires the invoked event. The app - // intends to do everything else: - // - Handle the invoked event - // - Handle the SplitView opening and closing - // - Handle aria-expanded being mutated by UIA (i.e. screen readers) - // - Keep the aria-controls attribute, aria-expanded attribute, and SplitView in sync - // - SplitView is provided via splitView property - // SplitViewPaneToggle keeps the SplitView, the aria-controls attribute, and the - // aria-expands attribute in sync. In this use case, apps typically won't listen - // to the invoked event (but it's still fired). - var ClassNames = { - splitViewPaneToggle: "win-splitviewpanetoggle" - }; - var EventNames = { - // Fires when the user invokes the button with mouse/keyboard/touch. Does not - // fire if the SplitViewPaneToggle's state changes due to UIA (i.e. aria-expanded - // being set) or due to the SplitView pane opening/closing. - invoked: "invoked" - }; - var Strings = { - get duplicateConstruction() { - return "Invalid argument: Controls may only be instantiated one time for each DOM element"; - }, - get badButtonElement() { - return "Invalid argument: The SplitViewPaneToggle's element must be a button element"; - } - }; - // The splitViewElement may not have a winControl associated with it yet in the case - // that the SplitViewPaneToggle was constructed before the SplitView. This may happen - // when WinJS.UI.processAll is used to construct the controls because the order of construction - // depends on the order in which the SplitView and SplitViewPaneToggle appear in the DOM. - function getSplitViewControl(splitViewElement) { - return (splitViewElement && splitViewElement["winControl"]); - } - function getPaneOpened(splitViewElement) { - var splitViewControl = getSplitViewControl(splitViewElement); - return splitViewControl ? splitViewControl.paneOpened : false; - } - /// - /// - /// Displays a button which is used for opening and closing a SplitView's pane. - /// - /// - /// - /// - /// ]]> - /// The SplitViewPaneToggle control itself. - /// - /// - var SplitViewPaneToggle = (function () { - function SplitViewPaneToggle(element, options) { - /// - /// - /// Creates a new SplitViewPaneToggle control. - /// - /// - /// The DOM element that hosts the SplitViewPaneToggle control. - /// - /// - /// An object that contains one or more property/value pairs to apply to the new control. - /// Each property of the options object corresponds to one of the control's properties or events. - /// Event names must begin with "on". For example, to provide a handler for the invoked event, - /// add a property named "oninvoked" to the options object and set its value to the event handler. - /// - /// - /// The new SplitViewPaneToggle. - /// - /// - if (options === void 0) { options = {}; } - // State private to _updateDom. No other method should make use of it. - // - // Nothing has been rendered yet so these are all initialized to undefined. Because - // they are undefined, the first time _updateDom is called, they will all be - // rendered. - this._updateDom_rendered = { - splitView: undefined - }; - // Check to make sure we weren't duplicated - if (element && element["winControl"]) { - throw new _ErrorFromName("WinJS.UI.SplitViewPaneToggle.DuplicateConstruction", Strings.duplicateConstruction); - } - this._onPaneStateSettledBound = this._onPaneStateSettled.bind(this); - this._ariaExpandedMutationObserver = new _ElementUtilities._MutationObserver(this._onAriaExpandedPropertyChanged.bind(this)); - this._initializeDom(element || _Global.document.createElement("button")); - // Private state - this._disposed = false; - // Default values - this.splitView = null; - _Control.setOptions(this, options); - this._initialized = true; - this._updateDom(); - } - Object.defineProperty(SplitViewPaneToggle.prototype, "element", { - /// - get: function () { - return this._dom.root; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SplitViewPaneToggle.prototype, "splitView", { - /// - get: function () { - return this._splitView; - }, - set: function (splitView) { - this._splitView = splitView; - if (splitView) { - this._opened = getPaneOpened(splitView); - } - this._updateDom(); - }, - enumerable: true, - configurable: true - }); - SplitViewPaneToggle.prototype.dispose = function () { - /// - /// - /// Disposes this control. - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - this._splitView && this._removeListeners(this._splitView); - }; - SplitViewPaneToggle.prototype._initializeDom = function (root) { - if (root.tagName !== "BUTTON") { - throw new _ErrorFromName("WinJS.UI.SplitViewPaneToggle.BadButtonElement", Strings.badButtonElement); - } - root["winControl"] = this; - _ElementUtilities.addClass(root, ClassNames.splitViewPaneToggle); - _ElementUtilities.addClass(root, "win-disposable"); - if (!root.hasAttribute("type")) { - root.type = "button"; - } - new _KeyboardBehavior._WinKeyboard(root); - root.addEventListener("click", this._onClick.bind(this)); - this._dom = { - root: root - }; - }; - SplitViewPaneToggle.prototype._updateDom = function () { - if (!this._initialized || this._disposed) { - return; - } - var rendered = this._updateDom_rendered; - if (this._splitView !== rendered.splitView) { - if (rendered.splitView) { - this._dom.root.removeAttribute("aria-controls"); - this._removeListeners(rendered.splitView); - } - if (this._splitView) { - _ElementUtilities._ensureId(this._splitView); - this._dom.root.setAttribute("aria-controls", this._splitView.id); - this._addListeners(this._splitView); - } - rendered.splitView = this._splitView; - } - // When no SplitView is provided, it's up to the app to manage aria-expanded. - if (this._splitView) { - // Always update aria-expanded and don't cache its most recently rendered value - // in _updateDom_rendered. The reason is that we're not the only ones that update - // aria-expanded. aria-expanded may be changed thru UIA APIs. Consequently, if we - // cached the last value we set in _updateDom_rendered, it may not reflect the current - // value in the DOM. - var expanded = this._opened ? "true" : "false"; - _ElementUtilities._setAttribute(this._dom.root, "aria-expanded", expanded); - // The splitView element may not have a winControl associated with it yet in the case - // that the SplitViewPaneToggle was constructed before the SplitView. This may happen - // when WinJS.UI.processAll is used to construct the controls because the order of construction - // depends on the order in which the SplitView and SplitViewPaneToggle appear in the DOM. - var splitViewControl = getSplitViewControl(this._splitView); - if (splitViewControl) { - splitViewControl.paneOpened = this._opened; - } - } - }; - SplitViewPaneToggle.prototype._addListeners = function (splitViewElement) { - splitViewElement.addEventListener("_openCloseStateSettled", this._onPaneStateSettledBound); - this._ariaExpandedMutationObserver.observe(this._dom.root, { - attributes: true, - attributeFilter: ["aria-expanded"] - }); - }; - SplitViewPaneToggle.prototype._removeListeners = function (splitViewElement) { - splitViewElement.removeEventListener("_openCloseStateSettled", this._onPaneStateSettledBound); - this._ariaExpandedMutationObserver.disconnect(); - }; - SplitViewPaneToggle.prototype._fireEvent = function (eventName) { - var eventObject = _Global.document.createEvent("CustomEvent"); - eventObject.initCustomEvent(eventName, true, false, null); - return this._dom.root.dispatchEvent(eventObject); - }; - // Inputs that change the SplitViewPaneToggle's state - // - SplitViewPaneToggle.prototype._onPaneStateSettled = function (eventObject) { - if (eventObject.target === this._splitView) { - this._opened = getPaneOpened(this._splitView); - this._updateDom(); - } - }; - // Called by tests. - SplitViewPaneToggle.prototype._onAriaExpandedPropertyChanged = function (mutations) { - var ariaExpanded = this._dom.root.getAttribute("aria-expanded") === "true"; - this._opened = ariaExpanded; - this._updateDom(); - }; - SplitViewPaneToggle.prototype._onClick = function (eventObject) { - this._invoked(); - }; - // Called by tests. - SplitViewPaneToggle.prototype._invoked = function () { - if (this._disposed) { - return; - } - if (this._splitView) { - this._opened = !this._opened; - this._updateDom(); - } - this._fireEvent(EventNames.invoked); - }; - SplitViewPaneToggle._ClassNames = ClassNames; - SplitViewPaneToggle.supportedForProcessing = true; - return SplitViewPaneToggle; - })(); - exports.SplitViewPaneToggle = SplitViewPaneToggle; - _Base.Class.mix(SplitViewPaneToggle, _Events.createEventProperties(EventNames.invoked)); - _Base.Class.mix(SplitViewPaneToggle, _Control.DOMEventMixin); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/SplitViewPaneToggle',["require", "exports", '../Core/_Base'], function (require, exports, _Base) { - var module = null; - _Base.Namespace.define("WinJS.UI", { - SplitViewPaneToggle: { - get: function () { - if (!module) { - require(["./SplitViewPaneToggle/_SplitViewPaneToggle"], function (m) { - module = m; - }); - } - return module.SplitViewPaneToggle; - } - } - }); -}); - -define('WinJS/Controls/AppBar/_Constants',["require", "exports", "../CommandingSurface/_Constants"], function (require, exports, _CommandingSurfaceConstants) { - // appbar class names - exports.ClassNames = { - controlCssClass: "win-appbar", - disposableCssClass: "win-disposable", - actionAreaCssClass: "win-appbar-actionarea", - overflowButtonCssClass: "win-appbar-overflowbutton", - spacerCssClass: "win-appbar-spacer", - ellipsisCssClass: "win-appbar-ellipsis", - overflowAreaCssClass: "win-appbar-overflowarea", - contentFlyoutCssClass: "win-appbar-contentflyout", - emptyappbarCssClass: "win-appbar-empty", - menuCssClass: "win-menu", - menuContainsToggleCommandClass: "win-menu-containstogglecommand", - openedClass: "win-appbar-opened", - closedClass: "win-appbar-closed", - noneClass: "win-appbar-closeddisplaynone", - minimalClass: "win-appbar-closeddisplayminimal", - compactClass: "win-appbar-closeddisplaycompact", - fullClass: "win-appbar-closeddisplayfull", - placementTopClass: "win-appbar-top", - placementBottomClass: "win-appbar-bottom", - }; - exports.EventNames = { - // AppBar - beforeOpen: "beforeopen", - afterOpen: "afteropen", - beforeClose: "beforeclose", - afterClose: "afterclose", - // AppBarCommand - commandPropertyMutated: "_commandpropertymutated", - }; - exports.controlMinWidth = _CommandingSurfaceConstants.controlMinWidth; - exports.defaultClosedDisplayMode = "compact"; - exports.defaultOpened = false; - exports.defaultPlacement = "bottom"; - // Constants for commands - exports.typeSeparator = "separator"; - exports.typeContent = "content"; - exports.typeButton = "button"; - exports.typeToggle = "toggle"; - exports.typeFlyout = "flyout"; - exports.commandSelector = ".win-command"; - exports.primaryCommandSection = "primary"; - exports.secondaryCommandSection = "secondary"; -}); - - -define('require-style!less/styles-appbar',[],function(){}); -define('WinJS/Controls/AppBar/_AppBar',["require", "exports", "../../Core/_Base", "../AppBar/_Constants", "../CommandingSurface", "../../Utilities/_Control", "../../Utilities/_Dispose", "../../Utilities/_ElementUtilities", "../../Core/_ErrorFromName", '../../Core/_Events', "../../Core/_Global", '../../Utilities/_KeyboardInfo', '../../_LightDismissService', '../../Promise', "../../Core/_Resources", '../../Utilities/_OpenCloseMachine', "../../Core/_WriteProfilerMark"], function (require, exports, _Base, _Constants, _CommandingSurface, _Control, _Dispose, _ElementUtilities, _ErrorFromName, _Events, _Global, _KeyboardInfo, _LightDismissService, Promise, _Resources, _OpenCloseMachine, _WriteProfilerMark) { - require(["require-style!less/styles-appbar"]); - "use strict"; - var keyboardInfo = _KeyboardInfo._KeyboardInfo; - var strings = { - get ariaLabel() { - return _Resources._getWinJSString("ui/appBarAriaLabel").value; - }, - get overflowButtonAriaLabel() { - return _Resources._getWinJSString("ui/appBarOverflowButtonAriaLabel").value; - }, - get mustContainCommands() { - return "The AppBar can only contain WinJS.UI.Command or WinJS.UI.AppBarCommand controls"; - }, - get duplicateConstruction() { - return "Invalid argument: Controls may only be instantiated one time for each DOM element"; - } - }; - var ClosedDisplayMode = { - /// - /// When the AppBar is closed, it is not visible and doesn't take up any space. - /// - none: "none", - /// - /// When the AppBar is closed, its height is reduced to the minimal height required to display only its overflowbutton. All other content in the AppBar is not displayed. - /// - minimal: "minimal", - /// - /// When the AppBar is closed, its height is reduced such that button commands are still visible, but their labels are hidden. - /// - compact: "compact", - /// - /// When the AppBar is closed, its height is always sized to content. - /// - full: "full", - }; - var closedDisplayModeClassMap = {}; - closedDisplayModeClassMap[ClosedDisplayMode.none] = _Constants.ClassNames.noneClass; - closedDisplayModeClassMap[ClosedDisplayMode.minimal] = _Constants.ClassNames.minimalClass; - closedDisplayModeClassMap[ClosedDisplayMode.compact] = _Constants.ClassNames.compactClass; - closedDisplayModeClassMap[ClosedDisplayMode.full] = _Constants.ClassNames.fullClass; - var Placement = { - /// - /// The AppBar appears at the top of the main view - /// - top: "top", - /// - /// The AppBar appears at the bottom of the main view - /// - bottom: "bottom", - }; - var placementClassMap = {}; - placementClassMap[Placement.top] = _Constants.ClassNames.placementTopClass; - placementClassMap[Placement.bottom] = _Constants.ClassNames.placementBottomClass; - // Versions of add/removeClass that are no ops when called with falsy class names. - function addClass(element, className) { - className && _ElementUtilities.addClass(element, className); - } - function removeClass(element, className) { - className && _ElementUtilities.removeClass(element, className); - } - /// - /// - /// Represents an appbar for displaying commands. - /// - /// - /// - /// - /// - /// - /// ]]> - /// The entire AppBar control. - /// The appbar overflow button. - /// The container for appbar commands that overflow. - /// - /// - var AppBar = (function () { - function AppBar(element, options) { - /// - /// - /// Creates a new AppBar control. - /// - /// - /// The DOM element that will host the control. - /// - /// - /// The set of properties and values to apply to the new AppBar control. - /// - /// - /// The new AppBar control. - /// - /// - var _this = this; - if (options === void 0) { options = {}; } - // State private to the _updateDomImpl family of method. No other methods should make use of it. - // - // Nothing has been rendered yet so these are all initialized to undefined. Because - // they are undefined, the first time _updateDomImpl is called, they will all be - // rendered. - this._updateDomImpl_renderedState = { - isOpenedMode: undefined, - placement: undefined, - closedDisplayMode: undefined, - adjustedOffsets: { top: undefined, bottom: undefined }, - }; - this._writeProfilerMark("constructor,StartTM"); - // Check to make sure we weren't duplicated - if (element && element["winControl"]) { - throw new _ErrorFromName("WinJS.UI.AppBar.DuplicateConstruction", strings.duplicateConstruction); - } - this._initializeDom(element || _Global.document.createElement("div")); - var stateMachine = new _OpenCloseMachine.OpenCloseMachine({ - eventElement: this.element, - onOpen: function () { - var openAnimation = _this._commandingSurface.createOpenAnimation(_this._getClosedHeight()); - // We're temporarily setting the AppBar's style from position=-ms-device-fixed to fixed to work around an animations bug in IE, - // where two AppBars will end up being rendered when animating instead of one. - // We need to recalculate our offsets relative to the top and bottom of the visible document because position fixed elements use layout viewport coordinates - // while position -ms-device-fixed use visual viewport coordinates.This difference in coordinate systems is especially pronounced if the IHM has caused the visual viewport to resize. - _this.element.style.position = "fixed"; - if (_this._placement === AppBar.Placement.top) { - _this.element.style.top = _KeyboardInfo._KeyboardInfo._layoutViewportCoords.visibleDocTop + "px"; - } - else { - _this.element.style.bottom = _KeyboardInfo._KeyboardInfo._layoutViewportCoords.visibleDocBottom + "px"; - } - _this._synchronousOpen(); - return openAnimation.execute().then(function () { - _this.element.style.position = ""; - _this.element.style.top = _this._adjustedOffsets.top; - _this.element.style.bottom = _this._adjustedOffsets.bottom; - }); - }, - onClose: function () { - var closeAnimation = _this._commandingSurface.createCloseAnimation(_this._getClosedHeight()); - // We're temporarily setting the AppBar's style from position=-ms-device-fixed to fixed to work around an animations bug in IE, - // where two AppBars will end up being rendered when animating instead of one. - // We need to recalculate our offsets relative to the top and bottom of the visible document because position fixed elements use layout viewport coordinates - // while position -ms-device-fixed use visual viewport coordinates.This difference in coordinate systems is especially pronounced if the IHM has caused the visual viewport to resize. - _this.element.style.position = "fixed"; - if (_this._placement === AppBar.Placement.top) { - _this.element.style.top = _KeyboardInfo._KeyboardInfo._layoutViewportCoords.visibleDocTop + "px"; - } - else { - _this.element.style.bottom = _KeyboardInfo._KeyboardInfo._layoutViewportCoords.visibleDocBottom + "px"; - } - return closeAnimation.execute().then(function () { - _this._synchronousClose(); - _this.element.style.position = ""; - _this.element.style.top = _this._adjustedOffsets.top; - _this.element.style.bottom = _this._adjustedOffsets.bottom; - }); - }, - onUpdateDom: function () { - _this._updateDomImpl(); - }, - onUpdateDomWithIsOpened: function (isOpened) { - _this._isOpenedMode = isOpened; - _this._updateDomImpl(); - } - }); - // Events - this._handleShowingKeyboardBound = this._handleShowingKeyboard.bind(this); - this._handleHidingKeyboardBound = this._handleHidingKeyboard.bind(this); - _ElementUtilities._inputPaneListener.addEventListener(this._dom.root, "showing", this._handleShowingKeyboardBound); - _ElementUtilities._inputPaneListener.addEventListener(this._dom.root, "hiding", this._handleHidingKeyboardBound); - // Initialize private state. - this._disposed = false; - this._cachedClosedHeight = null; - this._commandingSurface = new _CommandingSurface._CommandingSurface(this._dom.commandingSurfaceEl, { openCloseMachine: stateMachine }); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-actionarea"), _Constants.ClassNames.actionAreaCssClass); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowarea"), _Constants.ClassNames.overflowAreaCssClass); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowbutton"), _Constants.ClassNames.overflowButtonCssClass); - addClass(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-ellipsis"), _Constants.ClassNames.ellipsisCssClass); - this._isOpenedMode = _Constants.defaultOpened; - this._dismissable = new _LightDismissService.LightDismissableElement({ - element: this._dom.root, - tabIndex: this._dom.root.hasAttribute("tabIndex") ? this._dom.root.tabIndex : -1, - onLightDismiss: function () { - _this.close(); - } - }); - // Initialize public properties. - this.closedDisplayMode = _Constants.defaultClosedDisplayMode; - this.placement = _Constants.defaultPlacement; - this.opened = this._isOpenedMode; - _Control.setOptions(this, options); - // Exit the Init state. - _ElementUtilities._inDom(this.element).then(function () { - return _this._commandingSurface.initialized; - }).then(function () { - stateMachine.exitInit(); - _this._writeProfilerMark("constructor,StopTM"); - }); - } - Object.defineProperty(AppBar.prototype, "element", { - /// - get: function () { - return this._dom.root; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AppBar.prototype, "data", { - /// - /// Gets or sets the Binding List of WinJS.UI.Command for the AppBar. - /// - get: function () { - return this._commandingSurface.data; - }, - set: function (value) { - this._commandingSurface.data = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AppBar.prototype, "closedDisplayMode", { - /// - /// Gets or sets the closedDisplayMode for the AppBar. Values are "none", "minimal", "compact" and "full". - /// - get: function () { - return this._commandingSurface.closedDisplayMode; - }, - set: function (value) { - if (ClosedDisplayMode[value]) { - this._commandingSurface.closedDisplayMode = value; - this._cachedClosedHeight = null; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AppBar.prototype, "placement", { - /// - get: function () { - return this._placement; - }, - set: function (value) { - if (Placement[value] && this._placement !== value) { - this._placement = value; - switch (value) { - case Placement.top: - this._commandingSurface.overflowDirection = "bottom"; - break; - case Placement.bottom: - this._commandingSurface.overflowDirection = "top"; - break; - } - this._adjustedOffsets = this._computeAdjustedOffsets(); - this._commandingSurface.deferredDomUpate(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AppBar.prototype, "opened", { - /// - get: function () { - return this._commandingSurface.opened; - }, - set: function (value) { - this._commandingSurface.opened = value; - }, - enumerable: true, - configurable: true - }); - AppBar.prototype.open = function () { - /// - /// - /// Opens the AppBar - /// - /// - this._commandingSurface.open(); - }; - AppBar.prototype.close = function () { - /// - /// - /// Closes the AppBar - /// - /// - this._commandingSurface.close(); - }; - AppBar.prototype.dispose = function () { - /// - /// - /// Disposes this AppBar. - /// - /// - if (this._disposed) { - return; - } - this._disposed = true; - _LightDismissService.hidden(this._dismissable); - // Disposing the _commandingSurface will trigger dispose on its OpenCloseMachine - // and synchronously complete any animations that might have been running. - this._commandingSurface.dispose(); - _ElementUtilities._inputPaneListener.removeEventListener(this._dom.root, "showing", this._handleShowingKeyboardBound); - _ElementUtilities._inputPaneListener.removeEventListener(this._dom.root, "hiding", this._handleHidingKeyboardBound); - _Dispose.disposeSubTree(this.element); - }; - AppBar.prototype.forceLayout = function () { - /// - /// - /// Forces the AppBar to update its layout. Use this function when the window did not change size, but the container of the AppBar changed size. - /// - /// - this._commandingSurface.forceLayout(); - }; - AppBar.prototype.getCommandById = function (id) { - /// - /// - /// Retrieves the command with the specified ID from this AppBar. - /// If more than one command is found, this method returns the first command found. - /// - /// Id of the command to return. - /// - /// The command found, or null if no command is found. - /// - /// - return this._commandingSurface.getCommandById(id); - }; - AppBar.prototype.showOnlyCommands = function (commands) { - /// - /// - /// Show the specified commands, hiding all of the others in the AppBar. - /// - /// - /// An array of the commands to show. The array elements may be Command objects, or the string identifiers (IDs) of commands. - /// - /// - return this._commandingSurface.showOnlyCommands(commands); - }; - AppBar.prototype._writeProfilerMark = function (text) { - _WriteProfilerMark("WinJS.UI.AppBar:" + this._id + ":" + text); - }; - AppBar.prototype._initializeDom = function (root) { - this._writeProfilerMark("_intializeDom,info"); - // Attaching JS control to DOM element - root["winControl"] = this; - this._id = root.id || _ElementUtilities._uniqueID(root); - _ElementUtilities.addClass(root, _Constants.ClassNames.controlCssClass); - _ElementUtilities.addClass(root, _Constants.ClassNames.disposableCssClass); - // Make sure we have an ARIA role - var role = root.getAttribute("role"); - if (!role) { - root.setAttribute("role", "menubar"); - } - var label = root.getAttribute("aria-label"); - if (!label) { - root.setAttribute("aria-label", strings.ariaLabel); - } - // Create element for commandingSurface and reparent any declarative Commands. - // commandingSurface will parse child elements as AppBarCommands. - var commandingSurfaceEl = document.createElement("DIV"); - _ElementUtilities._reparentChildren(root, commandingSurfaceEl); - root.appendChild(commandingSurfaceEl); - this._dom = { - root: root, - commandingSurfaceEl: commandingSurfaceEl, - }; - }; - AppBar.prototype._handleShowingKeyboard = function (event) { - // If the IHM resized the window, we can rely on -ms-device-fixed positioning to remain visible. - // If the IHM does not resize the window we will need to adjust our offsets to avoid being occluded - // The IHM does not cause a window resize to happen right away, set a timeout to check if the viewport - // has been resized after enough time has passed for both the IHM animation, and scroll-into-view, to - // complete. - var _this = this; - // If focus is in the AppBar, tell the platform we will move ourselves. - if (this._dom.root.contains(_Global.document.activeElement)) { - var inputPaneEvent = event.detail.originalEvent; - inputPaneEvent.ensuredFocusedElementInView = true; - } - var duration = keyboardInfo._animationShowLength + keyboardInfo._scrollTimeout; - // Returns a promise for unit tests to verify the correct behavior after the timeout. - return Promise.timeout(duration).then(function () { - if (_this._shouldAdjustForShowingKeyboard() && !_this._disposed) { - _this._adjustedOffsets = _this._computeAdjustedOffsets(); - _this._commandingSurface.deferredDomUpate(); - } - }); - }; - AppBar.prototype._shouldAdjustForShowingKeyboard = function () { - // Overwriteable for unit tests - // Determines if an AppBar needs to adjust its position to move in response to a shown IHM, or if it can - // just ride the bottom of the visual viewport to remain visible. The latter requires that the IHM has - // caused the viewport to resize. - return keyboardInfo._visible && !keyboardInfo._isResized; - }; - AppBar.prototype._handleHidingKeyboard = function () { - // Make sure AppBar has the correct offsets since it could have been displaced by the IHM. - this._adjustedOffsets = this._computeAdjustedOffsets(); - this._commandingSurface.deferredDomUpate(); - }; - AppBar.prototype._computeAdjustedOffsets = function () { - // Position the AppBar element relative to the top or bottom edge of the visible - // document. - var offsets = { top: "", bottom: "" }; - if (this._placement === Placement.bottom) { - // If the IHM is open, the bottom of the visual viewport may or may not be occluded - offsets.bottom = keyboardInfo._visibleDocBottomOffset + "px"; - } - else if (this._placement === Placement.top) { - offsets.top = keyboardInfo._visibleDocTop + "px"; - } - return offsets; - }; - AppBar.prototype._synchronousOpen = function () { - this._isOpenedMode = true; - this._updateDomImpl(); - }; - AppBar.prototype._synchronousClose = function () { - this._isOpenedMode = false; - this._updateDomImpl(); - }; - AppBar.prototype._updateDomImpl = function () { - var rendered = this._updateDomImpl_renderedState; - if (rendered.isOpenedMode !== this._isOpenedMode) { - if (this._isOpenedMode) { - this._updateDomImpl_renderOpened(); - } - else { - this._updateDomImpl_renderClosed(); - } - rendered.isOpenedMode = this._isOpenedMode; - } - if (rendered.placement !== this.placement) { - removeClass(this._dom.root, placementClassMap[rendered.placement]); - addClass(this._dom.root, placementClassMap[this.placement]); - rendered.placement = this.placement; - } - if (rendered.closedDisplayMode !== this.closedDisplayMode) { - removeClass(this._dom.root, closedDisplayModeClassMap[rendered.closedDisplayMode]); - addClass(this._dom.root, closedDisplayModeClassMap[this.closedDisplayMode]); - rendered.closedDisplayMode = this.closedDisplayMode; - } - if (rendered.adjustedOffsets.top !== this._adjustedOffsets.top) { - this._dom.root.style.top = this._adjustedOffsets.top; - rendered.adjustedOffsets.top = this._adjustedOffsets.top; - } - if (rendered.adjustedOffsets.bottom !== this._adjustedOffsets.bottom) { - this._dom.root.style.bottom = this._adjustedOffsets.bottom; - rendered.adjustedOffsets.bottom = this._adjustedOffsets.bottom; - } - this._commandingSurface.updateDomImpl(); - }; - AppBar.prototype._getClosedHeight = function () { - if (this._cachedClosedHeight === null) { - var wasOpen = this._isOpenedMode; - if (this._isOpenedMode) { - this._synchronousClose(); - } - this._cachedClosedHeight = this._commandingSurface.getBoundingRects().commandingSurface.height; - if (wasOpen) { - this._synchronousOpen(); - } - } - return this._cachedClosedHeight; - }; - AppBar.prototype._updateDomImpl_renderOpened = function () { - addClass(this._dom.root, _Constants.ClassNames.openedClass); - removeClass(this._dom.root, _Constants.ClassNames.closedClass); - this._commandingSurface.synchronousOpen(); - _LightDismissService.shown(this._dismissable); // Call at the start of the open animation - }; - AppBar.prototype._updateDomImpl_renderClosed = function () { - addClass(this._dom.root, _Constants.ClassNames.closedClass); - removeClass(this._dom.root, _Constants.ClassNames.openedClass); - this._commandingSurface.synchronousClose(); - _LightDismissService.hidden(this._dismissable); // Call after the close animation - }; - /// - /// Display options for the AppBar when closed. - /// - AppBar.ClosedDisplayMode = ClosedDisplayMode; - /// - /// Display options for AppBar placement in relation to the main view. - /// - AppBar.Placement = Placement; - AppBar.supportedForProcessing = true; - return AppBar; - })(); - exports.AppBar = AppBar; - _Base.Class.mix(AppBar, _Events.createEventProperties(_Constants.EventNames.beforeOpen, _Constants.EventNames.afterOpen, _Constants.EventNames.beforeClose, _Constants.EventNames.afterClose)); - // addEventListener, removeEventListener, dispatchEvent - _Base.Class.mix(AppBar, _Control.DOMEventMixin); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -/// -define('WinJS/Controls/AppBar',["require", "exports", '../Core/_Base'], function (require, exports, _Base) { - var module = null; - _Base.Namespace.define("WinJS.UI", { - AppBar: { - get: function () { - if (!module) { - require(["./AppBar/_AppBar"], function (m) { - module = m; - }); - } - return module.AppBar; - } - } - }); -}); - -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. -define('ui',[ - 'WinJS/Core/_WinJS', - 'WinJS/VirtualizedDataSource', - 'WinJS/Controls/IntrinsicControls', - 'WinJS/Controls/ListView', - 'WinJS/Controls/FlipView', - 'WinJS/Controls/ItemContainer', - 'WinJS/Controls/Repeater', - 'WinJS/Controls/DatePicker', - 'WinJS/Controls/TimePicker', - 'WinJS/Controls/BackButton', - 'WinJS/Controls/Rating', - 'WinJS/Controls/ToggleSwitch', - 'WinJS/Controls/SemanticZoom', - 'WinJS/Controls/Pivot', - 'WinJS/Controls/Hub', - 'WinJS/Controls/Flyout', - 'WinJS/Controls/_LegacyAppBar', - 'WinJS/Controls/Menu', - 'WinJS/Controls/SearchBox', - 'WinJS/Controls/SettingsFlyout', - 'WinJS/Controls/NavBar', - 'WinJS/Controls/Tooltip', - 'WinJS/Controls/ViewBox', - 'WinJS/Controls/ContentDialog', - 'WinJS/Controls/SplitView', - 'WinJS/Controls/SplitViewPaneToggle', - 'WinJS/Controls/ToolBar', - 'WinJS/Controls/AppBar', - ], function (_WinJS) { - "use strict"; - - return _WinJS; -}); - - require(['WinJS/Core/_WinJS', 'ui'], function (_WinJS) { - // WinJS always publishes itself to global - globalObject.WinJS = _WinJS; - if (typeof module !== 'undefined') { - // This is a CommonJS context so publish to exports - module.exports = _WinJS; - } - }); - return globalObject.WinJS; - })); -}()); - diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/package.appxmanifest b/Samples/SimpleConversionDemo.UWP.WinJS/package.appxmanifest deleted file mode 100644 index 04818d1910..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/package.appxmanifest +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - UnitsNet.TestApps.Uwp.WinJS - Andreas - images\storelogo.png - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Samples/SimpleConversionDemo.UWP.WinJS/project.json b/Samples/SimpleConversionDemo.UWP.WinJS/project.json deleted file mode 100644 index 2f8c7f353b..0000000000 --- a/Samples/SimpleConversionDemo.UWP.WinJS/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "6.1.9", - "System.ValueTuple": "4.5.0", - "UnitsNet.WindowsRuntimeComponent": "4.7.0" - }, - "frameworks": { - "uap10.0": {} - }, - "runtimes": { - "win10-arm": {}, - "win10-arm-aot": {}, - "win10-x86": {}, - "win10-x86-aot": {}, - "win10-x64": {}, - "win10-x64-aot": {} - } -} \ No newline at end of file diff --git a/Samples/UnitConverter.Console/Program.cs b/Samples/UnitConverter.Console/Program.cs new file mode 100644 index 0000000000..7ba55aef09 --- /dev/null +++ b/Samples/UnitConverter.Console/Program.cs @@ -0,0 +1,6 @@ +using UnitsNet; +using static System.Console; +using static UnitsNet.Units.LengthUnit; + +WriteLine(Length.FromMeters(1).ToUnit(Centimeter)); // 100 cm +WriteLine(Length.Parse("100 cm").ToUnit(Meter)); // 1 m diff --git a/Samples/UnitConverter.Console/UnitConverter.Console.csproj b/Samples/UnitConverter.Console/UnitConverter.Console.csproj new file mode 100644 index 0000000000..82db681c45 --- /dev/null +++ b/Samples/UnitConverter.Console/UnitConverter.Console.csproj @@ -0,0 +1,14 @@ + + + + Exe + net6.0 + enable + enable + + + + + + + diff --git a/Samples/UnitConverter.Wpf/UnitConverter.Wpf/UnitConverter.Wpf.csproj b/Samples/UnitConverter.Wpf/UnitConverter.Wpf/UnitConverter.Wpf.csproj index 84df691425..29262603d0 100644 --- a/Samples/UnitConverter.Wpf/UnitConverter.Wpf/UnitConverter.Wpf.csproj +++ b/Samples/UnitConverter.Wpf/UnitConverter.Wpf/UnitConverter.Wpf.csproj @@ -8,7 +8,7 @@ WinExe UnitsNet.Samples.UnitConverter.Wpf UnitConverter.Wpf - v4.7.1 + v4.8 512 {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 4 diff --git a/Samples/WpfMVVMSample/build.bat b/Samples/WpfMVVMSample/build.bat deleted file mode 100644 index 266afed369..0000000000 --- a/Samples/WpfMVVMSample/build.bat +++ /dev/null @@ -1,12 +0,0 @@ -@echo off - -set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" - -for /f "usebackq tokens=*" %%i in (`%vswhere% -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do ( - set InstallDir=%%i -) - -if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" ( - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" /t:restore %* - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" %* -) \ No newline at end of file diff --git a/Samples/build.bat b/Samples/build.bat index e18b95c1fd..7b24eaf4ac 100644 --- a/Samples/build.bat +++ b/Samples/build.bat @@ -1,13 +1,3 @@ @echo off - -set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" - -for /f "usebackq tokens=*" %%i in (`%vswhere% -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do ( - set InstallDir=%%i -) - -echo %vswhere% - -if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" ( - "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" -verbosity:minimal %* -) \ No newline at end of file +setlocal enabledelayedexpansion +msbuild . \ No newline at end of file diff --git a/Samples/msbuild.cmd b/Samples/msbuild.cmd new file mode 100644 index 0000000000..bc17df2242 --- /dev/null +++ b/Samples/msbuild.cmd @@ -0,0 +1,10 @@ +@echo off +setlocal enabledelayedexpansion + +set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" + +for /f "usebackq tokens=*" %%i in (`%vswhere% -latest -prerelease -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe`) do ( + echo "%%i" + "%%i" %* + exit /b !errorlevel! +) \ No newline at end of file diff --git a/UnitsNet.Benchmark/Program.cs b/UnitsNet.Benchmark/Program.cs index f2b551b342..25d32af6e7 100644 --- a/UnitsNet.Benchmark/Program.cs +++ b/UnitsNet.Benchmark/Program.cs @@ -7,8 +7,8 @@ namespace UnitsNet.Benchmark [MemoryDiagnoser] public class UnitsNetBenchmarks { - private Length length = Length.FromMeters(3.0); - private IQuantity lengthIQuantity = Length.FromMeters(3.0); + private Length _length = Length.FromMeters(3.0); + private readonly IQuantity _lengthIQuantity = Length.FromMeters(3.0); [Benchmark] [BenchmarkCategory("Construction")] @@ -24,27 +24,27 @@ public class UnitsNetBenchmarks [Benchmark] [BenchmarkCategory("Transformation")] - public double ToProperty() => length.Centimeters; + public double ToProperty() => _length.Centimeters; [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double As() => length.As(LengthUnit.Centimeter); + public double As() => _length.As(LengthUnit.Centimeter); [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double As_SI() => length.As(UnitSystem.SI); + public double As_SI() => _length.As(UnitSystem.SI); [Benchmark] [BenchmarkCategory("Transformation, Quantity")] - public Length ToUnit() => length.ToUnit(LengthUnit.Centimeter); + public Length ToUnit() => _length.ToUnit(LengthUnit.Centimeter); [Benchmark] [BenchmarkCategory("Transformation, Quantity")] - public Length ToUnit_SI() => length.ToUnit(UnitSystem.SI); + public Length ToUnit_SI() => _length.ToUnit(UnitSystem.SI); [Benchmark] [BenchmarkCategory("ToString")] - public string ToStringTest() => length.ToString(); + public string ToStringTest() => _length.ToString(); [Benchmark] [BenchmarkCategory("Parsing")] @@ -52,11 +52,11 @@ public class UnitsNetBenchmarks [Benchmark] [BenchmarkCategory("Parsing")] - public bool TryParseValid() => Length.TryParse("3.0 m", out var l); + public bool TryParseValid() => Length.TryParse("3.0 m", out _); [Benchmark] [BenchmarkCategory("Parsing")] - public bool TryParseInvalid() => Length.TryParse("3.0 zoom", out var l); + public bool TryParseInvalid() => Length.TryParse("3.0 zoom", out _); [Benchmark] [BenchmarkCategory("Construction")] @@ -64,19 +64,19 @@ public class UnitsNetBenchmarks [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double IQuantity_As() => lengthIQuantity.As(LengthUnit.Centimeter); + public double IQuantity_As() => _lengthIQuantity.As(LengthUnit.Centimeter); [Benchmark] [BenchmarkCategory("Transformation, Value")] - public double IQuantity_As_SI() => lengthIQuantity.As(UnitSystem.SI); + public double IQuantity_As_SI() => _lengthIQuantity.As(UnitSystem.SI); [Benchmark] [BenchmarkCategory("Transformation, Quantity")] - public IQuantity IQuantity_ToUnit() => lengthIQuantity.ToUnit(LengthUnit.Centimeter); + public IQuantity IQuantity_ToUnit() => _lengthIQuantity.ToUnit(LengthUnit.Centimeter); [Benchmark] [BenchmarkCategory("ToString")] - public string IQuantity_ToStringTest() => lengthIQuantity.ToString(); + public string IQuantity_ToStringTest() => _lengthIQuantity.ToString(); } class Program diff --git a/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj b/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj index 56e21b23cd..7beb1cde43 100644 --- a/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj +++ b/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj @@ -1,9 +1,9 @@  Exe - net5.0;netcoreapp3.1;netcoreapp2.1;net48;net472 + net6.0;net48 4.0.0.0 - 4.0.0.0 + 4.0.0.0 UnitsNet.Benchmark UnitsNet.Benchmark UnitsNet diff --git a/UnitsNet.NanoFramework/GeneratedCode/Acceleration/UnitsNet.NanoFramework.Acceleration.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Acceleration/UnitsNet.NanoFramework.Acceleration.nuspec index d874fdfe79..f57f4d556e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Acceleration/UnitsNet.NanoFramework.Acceleration.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Acceleration/UnitsNet.NanoFramework.Acceleration.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Acceleration - 4.149.0 + 5.0.0-alpha006 Units.NET Acceleration - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component acceleration + nanoframework acceleration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/AmountOfSubstance/UnitsNet.NanoFramework.AmountOfSubstance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/AmountOfSubstance/UnitsNet.NanoFramework.AmountOfSubstance.nuspec index b5e2a815e5..cc5dc3b0a1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/AmountOfSubstance/UnitsNet.NanoFramework.AmountOfSubstance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/AmountOfSubstance/UnitsNet.NanoFramework.AmountOfSubstance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.AmountOfSubstance - 4.149.0 + 5.0.0-alpha006 Units.NET AmountOfSubstance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component amountofsubstance + nanoframework amountofsubstance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/AmplitudeRatio/UnitsNet.NanoFramework.AmplitudeRatio.nuspec b/UnitsNet.NanoFramework/GeneratedCode/AmplitudeRatio/UnitsNet.NanoFramework.AmplitudeRatio.nuspec index a19946c1a5..19ecbdffce 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/AmplitudeRatio/UnitsNet.NanoFramework.AmplitudeRatio.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/AmplitudeRatio/UnitsNet.NanoFramework.AmplitudeRatio.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.AmplitudeRatio - 4.149.0 + 5.0.0-alpha006 Units.NET AmplitudeRatio - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component amplituderatio + nanoframework amplituderatio unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Angle/UnitsNet.NanoFramework.Angle.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Angle/UnitsNet.NanoFramework.Angle.nuspec index e9eb4d295c..d1e47abadd 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Angle/UnitsNet.NanoFramework.Angle.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Angle/UnitsNet.NanoFramework.Angle.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Angle - 4.149.0 + 5.0.0-alpha006 Units.NET Angle - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component angle + nanoframework angle unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ApparentEnergy/UnitsNet.NanoFramework.ApparentEnergy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ApparentEnergy/UnitsNet.NanoFramework.ApparentEnergy.nuspec index b23c0196af..446c4274c6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ApparentEnergy/UnitsNet.NanoFramework.ApparentEnergy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ApparentEnergy/UnitsNet.NanoFramework.ApparentEnergy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ApparentEnergy - 4.149.0 + 5.0.0-alpha006 Units.NET ApparentEnergy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component apparentenergy + nanoframework apparentenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ApparentPower/UnitsNet.NanoFramework.ApparentPower.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ApparentPower/UnitsNet.NanoFramework.ApparentPower.nuspec index 73f0a29f81..095f17421f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ApparentPower/UnitsNet.NanoFramework.ApparentPower.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ApparentPower/UnitsNet.NanoFramework.ApparentPower.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ApparentPower - 4.149.0 + 5.0.0-alpha006 Units.NET ApparentPower - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component apparentpower + nanoframework apparentpower unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Area/UnitsNet.NanoFramework.Area.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Area/UnitsNet.NanoFramework.Area.nuspec index 1f3dc9f2b7..c92217ec8b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Area/UnitsNet.NanoFramework.Area.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Area/UnitsNet.NanoFramework.Area.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Area - 4.149.0 + 5.0.0-alpha006 Units.NET Area - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component area + nanoframework area unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/AreaDensity/UnitsNet.NanoFramework.AreaDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/AreaDensity/UnitsNet.NanoFramework.AreaDensity.nuspec index cc1188f5cb..ec72b39edb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/AreaDensity/UnitsNet.NanoFramework.AreaDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/AreaDensity/UnitsNet.NanoFramework.AreaDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.AreaDensity - 4.149.0 + 5.0.0-alpha006 Units.NET AreaDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component areadensity + nanoframework areadensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/AreaMomentOfInertia/UnitsNet.NanoFramework.AreaMomentOfInertia.nuspec b/UnitsNet.NanoFramework/GeneratedCode/AreaMomentOfInertia/UnitsNet.NanoFramework.AreaMomentOfInertia.nuspec index a46bff6d25..47303c671a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/AreaMomentOfInertia/UnitsNet.NanoFramework.AreaMomentOfInertia.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/AreaMomentOfInertia/UnitsNet.NanoFramework.AreaMomentOfInertia.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.AreaMomentOfInertia - 4.149.0 + 5.0.0-alpha006 Units.NET AreaMomentOfInertia - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component areamomentofinertia + nanoframework areamomentofinertia unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/BitRate/UnitsNet.NanoFramework.BitRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/BitRate/UnitsNet.NanoFramework.BitRate.nuspec index e0293581ba..6700e9ab1c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/BitRate/UnitsNet.NanoFramework.BitRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/BitRate/UnitsNet.NanoFramework.BitRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.BitRate - 4.149.0 + 5.0.0-alpha006 Units.NET BitRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component bitrate + nanoframework bitrate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/BrakeSpecificFuelConsumption/UnitsNet.NanoFramework.BrakeSpecificFuelConsumption.nuspec b/UnitsNet.NanoFramework/GeneratedCode/BrakeSpecificFuelConsumption/UnitsNet.NanoFramework.BrakeSpecificFuelConsumption.nuspec index 6659d99427..c12999cf54 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/BrakeSpecificFuelConsumption/UnitsNet.NanoFramework.BrakeSpecificFuelConsumption.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/BrakeSpecificFuelConsumption/UnitsNet.NanoFramework.BrakeSpecificFuelConsumption.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.BrakeSpecificFuelConsumption - 4.149.0 + 5.0.0-alpha006 Units.NET BrakeSpecificFuelConsumption - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component brakespecificfuelconsumption + nanoframework brakespecificfuelconsumption unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Capacitance/UnitsNet.NanoFramework.Capacitance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Capacitance/UnitsNet.NanoFramework.Capacitance.nuspec index ae40fed0a7..a7c17a1d6e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Capacitance/UnitsNet.NanoFramework.Capacitance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Capacitance/UnitsNet.NanoFramework.Capacitance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Capacitance - 4.149.0 + 5.0.0-alpha006 Units.NET Capacitance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component capacitance + nanoframework capacitance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/CoefficientOfThermalExpansion/UnitsNet.NanoFramework.CoefficientOfThermalExpansion.nuspec b/UnitsNet.NanoFramework/GeneratedCode/CoefficientOfThermalExpansion/UnitsNet.NanoFramework.CoefficientOfThermalExpansion.nuspec index bb4311692b..8a9503d767 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/CoefficientOfThermalExpansion/UnitsNet.NanoFramework.CoefficientOfThermalExpansion.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/CoefficientOfThermalExpansion/UnitsNet.NanoFramework.CoefficientOfThermalExpansion.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.CoefficientOfThermalExpansion - 4.149.0 + 5.0.0-alpha006 Units.NET CoefficientOfThermalExpansion - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component coefficientofthermalexpansion + nanoframework coefficientofthermalexpansion unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Compressibility/UnitsNet.NanoFramework.Compressibility.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Compressibility/UnitsNet.NanoFramework.Compressibility.nuspec index 827a4609b0..e70d87c235 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Compressibility/UnitsNet.NanoFramework.Compressibility.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Compressibility/UnitsNet.NanoFramework.Compressibility.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Compressibility - 4.149.0 + 5.0.0-alpha006 Units.NET Compressibility - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component compressibility + nanoframework compressibility unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Density/UnitsNet.NanoFramework.Density.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Density/UnitsNet.NanoFramework.Density.nuspec index ffa7e840d3..370ad8735e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Density/UnitsNet.NanoFramework.Density.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Density/UnitsNet.NanoFramework.Density.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Density - 4.149.0 + 5.0.0-alpha006 Units.NET Density - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component density + nanoframework density unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Duration/UnitsNet.NanoFramework.Duration.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Duration/UnitsNet.NanoFramework.Duration.nuspec index daa49a2249..e0099ab649 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Duration/UnitsNet.NanoFramework.Duration.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Duration/UnitsNet.NanoFramework.Duration.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Duration - 4.149.0 + 5.0.0-alpha006 Units.NET Duration - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component duration + nanoframework duration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/DynamicViscosity/UnitsNet.NanoFramework.DynamicViscosity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/DynamicViscosity/UnitsNet.NanoFramework.DynamicViscosity.nuspec index 220d7c86f1..d2473939c4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/DynamicViscosity/UnitsNet.NanoFramework.DynamicViscosity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/DynamicViscosity/UnitsNet.NanoFramework.DynamicViscosity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.DynamicViscosity - 4.149.0 + 5.0.0-alpha006 Units.NET DynamicViscosity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component dynamicviscosity + nanoframework dynamicviscosity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricAdmittance/UnitsNet.NanoFramework.ElectricAdmittance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricAdmittance/UnitsNet.NanoFramework.ElectricAdmittance.nuspec index ca2c2bb8da..b2b871edaa 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricAdmittance/UnitsNet.NanoFramework.ElectricAdmittance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricAdmittance/UnitsNet.NanoFramework.ElectricAdmittance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricAdmittance - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricAdmittance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricadmittance + nanoframework electricadmittance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricCharge/UnitsNet.NanoFramework.ElectricCharge.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricCharge/UnitsNet.NanoFramework.ElectricCharge.nuspec index 3d1aea991d..93f22057ea 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricCharge/UnitsNet.NanoFramework.ElectricCharge.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricCharge/UnitsNet.NanoFramework.ElectricCharge.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricCharge - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricCharge - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electriccharge + nanoframework electriccharge unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricChargeDensity/UnitsNet.NanoFramework.ElectricChargeDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricChargeDensity/UnitsNet.NanoFramework.ElectricChargeDensity.nuspec index 425d1c4855..d0b34da395 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricChargeDensity/UnitsNet.NanoFramework.ElectricChargeDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricChargeDensity/UnitsNet.NanoFramework.ElectricChargeDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricChargeDensity - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricChargeDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricchargedensity + nanoframework electricchargedensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricConductance/UnitsNet.NanoFramework.ElectricConductance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricConductance/UnitsNet.NanoFramework.ElectricConductance.nuspec index e4a4fb7bb5..4c292127b1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricConductance/UnitsNet.NanoFramework.ElectricConductance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricConductance/UnitsNet.NanoFramework.ElectricConductance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricConductance - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricConductance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricconductance + nanoframework electricconductance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricConductivity/UnitsNet.NanoFramework.ElectricConductivity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricConductivity/UnitsNet.NanoFramework.ElectricConductivity.nuspec index 6996bd466d..57b7d5d90a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricConductivity/UnitsNet.NanoFramework.ElectricConductivity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricConductivity/UnitsNet.NanoFramework.ElectricConductivity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricConductivity - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricConductivity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricconductivity + nanoframework electricconductivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrent/UnitsNet.NanoFramework.ElectricCurrent.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrent/UnitsNet.NanoFramework.ElectricCurrent.nuspec index b926139632..2fa448b60c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrent/UnitsNet.NanoFramework.ElectricCurrent.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrent/UnitsNet.NanoFramework.ElectricCurrent.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricCurrent - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricCurrent - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electriccurrent + nanoframework electriccurrent unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentDensity/UnitsNet.NanoFramework.ElectricCurrentDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentDensity/UnitsNet.NanoFramework.ElectricCurrentDensity.nuspec index b3207baaf6..ed8c952851 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentDensity/UnitsNet.NanoFramework.ElectricCurrentDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentDensity/UnitsNet.NanoFramework.ElectricCurrentDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricCurrentDensity - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricCurrentDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electriccurrentdensity + nanoframework electriccurrentdensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentGradient/UnitsNet.NanoFramework.ElectricCurrentGradient.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentGradient/UnitsNet.NanoFramework.ElectricCurrentGradient.nuspec index 0d6d3340a1..7164f23981 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentGradient/UnitsNet.NanoFramework.ElectricCurrentGradient.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricCurrentGradient/UnitsNet.NanoFramework.ElectricCurrentGradient.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricCurrentGradient - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricCurrentGradient - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electriccurrentgradient + nanoframework electriccurrentgradient unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricField/UnitsNet.NanoFramework.ElectricField.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricField/UnitsNet.NanoFramework.ElectricField.nuspec index 1b51eda3b7..96508b853a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricField/UnitsNet.NanoFramework.ElectricField.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricField/UnitsNet.NanoFramework.ElectricField.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricField - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricField - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricfield + nanoframework electricfield unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricInductance/UnitsNet.NanoFramework.ElectricInductance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricInductance/UnitsNet.NanoFramework.ElectricInductance.nuspec index 4c6804f855..45ffc9e9fb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricInductance/UnitsNet.NanoFramework.ElectricInductance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricInductance/UnitsNet.NanoFramework.ElectricInductance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricInductance - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricInductance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricinductance + nanoframework electricinductance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotential/UnitsNet.NanoFramework.ElectricPotential.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotential/UnitsNet.NanoFramework.ElectricPotential.nuspec index 87494827fe..511cbe67d0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotential/UnitsNet.NanoFramework.ElectricPotential.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotential/UnitsNet.NanoFramework.ElectricPotential.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricPotential - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricPotential - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricpotential + nanoframework electricpotential unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialAc/UnitsNet.NanoFramework.ElectricPotentialAc.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialAc/UnitsNet.NanoFramework.ElectricPotentialAc.nuspec index 1737337d5d..919ed09470 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialAc/UnitsNet.NanoFramework.ElectricPotentialAc.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialAc/UnitsNet.NanoFramework.ElectricPotentialAc.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricPotentialAc - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricPotentialAc - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricpotentialac + nanoframework electricpotentialac unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialChangeRate/UnitsNet.NanoFramework.ElectricPotentialChangeRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialChangeRate/UnitsNet.NanoFramework.ElectricPotentialChangeRate.nuspec index 24b099d2cc..9f608b3c28 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialChangeRate/UnitsNet.NanoFramework.ElectricPotentialChangeRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialChangeRate/UnitsNet.NanoFramework.ElectricPotentialChangeRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricPotentialChangeRate - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricPotentialChangeRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricpotentialchangerate + nanoframework electricpotentialchangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialDc/UnitsNet.NanoFramework.ElectricPotentialDc.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialDc/UnitsNet.NanoFramework.ElectricPotentialDc.nuspec index 7285e84622..cdcc61cd87 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialDc/UnitsNet.NanoFramework.ElectricPotentialDc.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricPotentialDc/UnitsNet.NanoFramework.ElectricPotentialDc.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricPotentialDc - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricPotentialDc - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricpotentialdc + nanoframework electricpotentialdc unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricResistance/UnitsNet.NanoFramework.ElectricResistance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricResistance/UnitsNet.NanoFramework.ElectricResistance.nuspec index 6ff103ce95..ed165d1442 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricResistance/UnitsNet.NanoFramework.ElectricResistance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricResistance/UnitsNet.NanoFramework.ElectricResistance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricResistance - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricResistance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricresistance + nanoframework electricresistance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricResistivity/UnitsNet.NanoFramework.ElectricResistivity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricResistivity/UnitsNet.NanoFramework.ElectricResistivity.nuspec index ee7636f045..9d06bf2a2d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricResistivity/UnitsNet.NanoFramework.ElectricResistivity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricResistivity/UnitsNet.NanoFramework.ElectricResistivity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricResistivity - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricResistivity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricresistivity + nanoframework electricresistivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ElectricSurfaceChargeDensity/UnitsNet.NanoFramework.ElectricSurfaceChargeDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ElectricSurfaceChargeDensity/UnitsNet.NanoFramework.ElectricSurfaceChargeDensity.nuspec index 1e13db451f..9e5c76adcf 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ElectricSurfaceChargeDensity/UnitsNet.NanoFramework.ElectricSurfaceChargeDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ElectricSurfaceChargeDensity/UnitsNet.NanoFramework.ElectricSurfaceChargeDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ElectricSurfaceChargeDensity - 4.149.0 + 5.0.0-alpha006 Units.NET ElectricSurfaceChargeDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component electricsurfacechargedensity + nanoframework electricsurfacechargedensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Energy/UnitsNet.NanoFramework.Energy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Energy/UnitsNet.NanoFramework.Energy.nuspec index a900f86639..87d4974861 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Energy/UnitsNet.NanoFramework.Energy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Energy/UnitsNet.NanoFramework.Energy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Energy - 4.149.0 + 5.0.0-alpha006 Units.NET Energy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component energy + nanoframework energy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/EnergyDensity/UnitsNet.NanoFramework.EnergyDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/EnergyDensity/UnitsNet.NanoFramework.EnergyDensity.nuspec index 3c42a368a7..0a2bec7b1b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/EnergyDensity/UnitsNet.NanoFramework.EnergyDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/EnergyDensity/UnitsNet.NanoFramework.EnergyDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.EnergyDensity - 4.149.0 + 5.0.0-alpha006 Units.NET EnergyDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component energydensity + nanoframework energydensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Entropy/UnitsNet.NanoFramework.Entropy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Entropy/UnitsNet.NanoFramework.Entropy.nuspec index f73c241788..c2a0612073 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Entropy/UnitsNet.NanoFramework.Entropy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Entropy/UnitsNet.NanoFramework.Entropy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Entropy - 4.149.0 + 5.0.0-alpha006 Units.NET Entropy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component entropy + nanoframework entropy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Force/UnitsNet.NanoFramework.Force.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Force/UnitsNet.NanoFramework.Force.nuspec index 8b4e92757d..7bfefad299 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Force/UnitsNet.NanoFramework.Force.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Force/UnitsNet.NanoFramework.Force.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Force - 4.149.0 + 5.0.0-alpha006 Units.NET Force - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component force + nanoframework force unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ForceChangeRate/UnitsNet.NanoFramework.ForceChangeRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ForceChangeRate/UnitsNet.NanoFramework.ForceChangeRate.nuspec index bab4c82242..f2a396cbd7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ForceChangeRate/UnitsNet.NanoFramework.ForceChangeRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ForceChangeRate/UnitsNet.NanoFramework.ForceChangeRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ForceChangeRate - 4.149.0 + 5.0.0-alpha006 Units.NET ForceChangeRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component forcechangerate + nanoframework forcechangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ForcePerLength/UnitsNet.NanoFramework.ForcePerLength.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ForcePerLength/UnitsNet.NanoFramework.ForcePerLength.nuspec index 1cecc4ace0..0444b620e2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ForcePerLength/UnitsNet.NanoFramework.ForcePerLength.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ForcePerLength/UnitsNet.NanoFramework.ForcePerLength.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ForcePerLength - 4.149.0 + 5.0.0-alpha006 Units.NET ForcePerLength - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component forceperlength + nanoframework forceperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Frequency/UnitsNet.NanoFramework.Frequency.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Frequency/UnitsNet.NanoFramework.Frequency.nuspec index c419b9551f..ee34f3a6b1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Frequency/UnitsNet.NanoFramework.Frequency.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Frequency/UnitsNet.NanoFramework.Frequency.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Frequency - 4.149.0 + 5.0.0-alpha006 Units.NET Frequency - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component frequency + nanoframework frequency unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/FuelEfficiency/UnitsNet.NanoFramework.FuelEfficiency.nuspec b/UnitsNet.NanoFramework/GeneratedCode/FuelEfficiency/UnitsNet.NanoFramework.FuelEfficiency.nuspec index 0a54ca4c71..caa857b2bd 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/FuelEfficiency/UnitsNet.NanoFramework.FuelEfficiency.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/FuelEfficiency/UnitsNet.NanoFramework.FuelEfficiency.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.FuelEfficiency - 4.149.0 + 5.0.0-alpha006 Units.NET FuelEfficiency - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component fuelefficiency + nanoframework fuelefficiency unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/HeatFlux/UnitsNet.NanoFramework.HeatFlux.nuspec b/UnitsNet.NanoFramework/GeneratedCode/HeatFlux/UnitsNet.NanoFramework.HeatFlux.nuspec index 213e563dee..3eb1b247b8 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/HeatFlux/UnitsNet.NanoFramework.HeatFlux.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/HeatFlux/UnitsNet.NanoFramework.HeatFlux.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.HeatFlux - 4.149.0 + 5.0.0-alpha006 Units.NET HeatFlux - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component heatflux + nanoframework heatflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/HeatTransferCoefficient/UnitsNet.NanoFramework.HeatTransferCoefficient.nuspec b/UnitsNet.NanoFramework/GeneratedCode/HeatTransferCoefficient/UnitsNet.NanoFramework.HeatTransferCoefficient.nuspec index 46a201ecb1..548e66b807 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/HeatTransferCoefficient/UnitsNet.NanoFramework.HeatTransferCoefficient.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/HeatTransferCoefficient/UnitsNet.NanoFramework.HeatTransferCoefficient.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.HeatTransferCoefficient - 4.149.0 + 5.0.0-alpha006 Units.NET HeatTransferCoefficient - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component heattransfercoefficient + nanoframework heattransfercoefficient unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Illuminance/UnitsNet.NanoFramework.Illuminance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Illuminance/UnitsNet.NanoFramework.Illuminance.nuspec index 63a09c917e..de69ea8843 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Illuminance/UnitsNet.NanoFramework.Illuminance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Illuminance/UnitsNet.NanoFramework.Illuminance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Illuminance - 4.149.0 + 5.0.0-alpha006 Units.NET Illuminance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component illuminance + nanoframework illuminance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Information/UnitsNet.NanoFramework.Information.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Information/UnitsNet.NanoFramework.Information.nuspec index 4aed918fd7..29aed3fd4c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Information/UnitsNet.NanoFramework.Information.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Information/UnitsNet.NanoFramework.Information.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Information - 4.149.0 + 5.0.0-alpha006 Units.NET Information - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component information + nanoframework information unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Irradiance/UnitsNet.NanoFramework.Irradiance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Irradiance/UnitsNet.NanoFramework.Irradiance.nuspec index 3aefc76156..d44c1b68a5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Irradiance/UnitsNet.NanoFramework.Irradiance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Irradiance/UnitsNet.NanoFramework.Irradiance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Irradiance - 4.149.0 + 5.0.0-alpha006 Units.NET Irradiance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component irradiance + nanoframework irradiance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Irradiation/UnitsNet.NanoFramework.Irradiation.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Irradiation/UnitsNet.NanoFramework.Irradiation.nuspec index e61e322c85..a2ef2cf391 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Irradiation/UnitsNet.NanoFramework.Irradiation.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Irradiation/UnitsNet.NanoFramework.Irradiation.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Irradiation - 4.149.0 + 5.0.0-alpha006 Units.NET Irradiation - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component irradiation + nanoframework irradiation unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Jerk/UnitsNet.NanoFramework.Jerk.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Jerk/UnitsNet.NanoFramework.Jerk.nuspec index fa549f250d..3c80d53f53 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Jerk/UnitsNet.NanoFramework.Jerk.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Jerk/UnitsNet.NanoFramework.Jerk.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Jerk - 4.149.0 + 5.0.0-alpha006 Units.NET Jerk - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component jerk + nanoframework jerk unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/KinematicViscosity/UnitsNet.NanoFramework.KinematicViscosity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/KinematicViscosity/UnitsNet.NanoFramework.KinematicViscosity.nuspec index e034a1a4f5..3b296a88ac 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/KinematicViscosity/UnitsNet.NanoFramework.KinematicViscosity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/KinematicViscosity/UnitsNet.NanoFramework.KinematicViscosity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.KinematicViscosity - 4.149.0 + 5.0.0-alpha006 Units.NET KinematicViscosity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component kinematicviscosity + nanoframework kinematicviscosity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/LapseRate/UnitsNet.NanoFramework.LapseRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/LapseRate/UnitsNet.NanoFramework.LapseRate.nuspec index 47e3be0e39..e2c1f55189 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/LapseRate/UnitsNet.NanoFramework.LapseRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/LapseRate/UnitsNet.NanoFramework.LapseRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.LapseRate - 4.149.0 + 5.0.0-alpha006 Units.NET LapseRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component lapserate + nanoframework lapserate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Length/UnitsNet.NanoFramework.Length.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Length/UnitsNet.NanoFramework.Length.nuspec index 0301940cfc..d0234d69a8 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Length/UnitsNet.NanoFramework.Length.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Length/UnitsNet.NanoFramework.Length.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Length - 4.149.0 + 5.0.0-alpha006 Units.NET Length - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component length + nanoframework length unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Level/UnitsNet.NanoFramework.Level.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Level/UnitsNet.NanoFramework.Level.nuspec index 9af3015132..64e716c4e2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Level/UnitsNet.NanoFramework.Level.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Level/UnitsNet.NanoFramework.Level.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Level - 4.149.0 + 5.0.0-alpha006 Units.NET Level - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component level + nanoframework level unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/LinearDensity/UnitsNet.NanoFramework.LinearDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/LinearDensity/UnitsNet.NanoFramework.LinearDensity.nuspec index 28e22c8b21..84731f32f9 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/LinearDensity/UnitsNet.NanoFramework.LinearDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/LinearDensity/UnitsNet.NanoFramework.LinearDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.LinearDensity - 4.149.0 + 5.0.0-alpha006 Units.NET LinearDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component lineardensity + nanoframework lineardensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/LinearPowerDensity/UnitsNet.NanoFramework.LinearPowerDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/LinearPowerDensity/UnitsNet.NanoFramework.LinearPowerDensity.nuspec index 42a02fc9e3..624bb6c8b7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/LinearPowerDensity/UnitsNet.NanoFramework.LinearPowerDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/LinearPowerDensity/UnitsNet.NanoFramework.LinearPowerDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.LinearPowerDensity - 4.149.0 + 5.0.0-alpha006 Units.NET LinearPowerDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component linearpowerdensity + nanoframework linearpowerdensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Luminance/UnitsNet.NanoFramework.Luminance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Luminance/UnitsNet.NanoFramework.Luminance.nuspec index f60e91a733..11c24695b7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Luminance/UnitsNet.NanoFramework.Luminance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Luminance/UnitsNet.NanoFramework.Luminance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Luminance - 4.149.0 + 5.0.0-alpha006 Units.NET Luminance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component luminance + nanoframework luminance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Luminosity/UnitsNet.NanoFramework.Luminosity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Luminosity/UnitsNet.NanoFramework.Luminosity.nuspec index efd12fcd64..da32a0d41f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Luminosity/UnitsNet.NanoFramework.Luminosity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Luminosity/UnitsNet.NanoFramework.Luminosity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Luminosity - 4.149.0 + 5.0.0-alpha006 Units.NET Luminosity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component luminosity + nanoframework luminosity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/LuminousFlux/UnitsNet.NanoFramework.LuminousFlux.nuspec b/UnitsNet.NanoFramework/GeneratedCode/LuminousFlux/UnitsNet.NanoFramework.LuminousFlux.nuspec index 8579c8c2e2..f5301fb6c8 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/LuminousFlux/UnitsNet.NanoFramework.LuminousFlux.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/LuminousFlux/UnitsNet.NanoFramework.LuminousFlux.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.LuminousFlux - 4.149.0 + 5.0.0-alpha006 Units.NET LuminousFlux - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component luminousflux + nanoframework luminousflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/LuminousIntensity/UnitsNet.NanoFramework.LuminousIntensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/LuminousIntensity/UnitsNet.NanoFramework.LuminousIntensity.nuspec index 98eeb4967a..b26f171a6a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/LuminousIntensity/UnitsNet.NanoFramework.LuminousIntensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/LuminousIntensity/UnitsNet.NanoFramework.LuminousIntensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.LuminousIntensity - 4.149.0 + 5.0.0-alpha006 Units.NET LuminousIntensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component luminousintensity + nanoframework luminousintensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MagneticField/UnitsNet.NanoFramework.MagneticField.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MagneticField/UnitsNet.NanoFramework.MagneticField.nuspec index 30465c2cc1..eb1173c643 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MagneticField/UnitsNet.NanoFramework.MagneticField.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MagneticField/UnitsNet.NanoFramework.MagneticField.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MagneticField - 4.149.0 + 5.0.0-alpha006 Units.NET MagneticField - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component magneticfield + nanoframework magneticfield unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MagneticFlux/UnitsNet.NanoFramework.MagneticFlux.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MagneticFlux/UnitsNet.NanoFramework.MagneticFlux.nuspec index b318df2a7f..3b7651d310 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MagneticFlux/UnitsNet.NanoFramework.MagneticFlux.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MagneticFlux/UnitsNet.NanoFramework.MagneticFlux.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MagneticFlux - 4.149.0 + 5.0.0-alpha006 Units.NET MagneticFlux - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component magneticflux + nanoframework magneticflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Magnetization/UnitsNet.NanoFramework.Magnetization.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Magnetization/UnitsNet.NanoFramework.Magnetization.nuspec index 0e393e687f..a9196414f4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Magnetization/UnitsNet.NanoFramework.Magnetization.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Magnetization/UnitsNet.NanoFramework.Magnetization.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Magnetization - 4.149.0 + 5.0.0-alpha006 Units.NET Magnetization - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component magnetization + nanoframework magnetization unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Mass/UnitsNet.NanoFramework.Mass.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Mass/UnitsNet.NanoFramework.Mass.nuspec index 892eed0fa1..7a79bb5c84 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Mass/UnitsNet.NanoFramework.Mass.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Mass/UnitsNet.NanoFramework.Mass.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Mass - 4.149.0 + 5.0.0-alpha006 Units.NET Mass - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component mass + nanoframework mass unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MassConcentration/UnitsNet.NanoFramework.MassConcentration.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MassConcentration/UnitsNet.NanoFramework.MassConcentration.nuspec index 1d63c35d26..72294257ce 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MassConcentration/UnitsNet.NanoFramework.MassConcentration.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MassConcentration/UnitsNet.NanoFramework.MassConcentration.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MassConcentration - 4.149.0 + 5.0.0-alpha006 Units.NET MassConcentration - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component massconcentration + nanoframework massconcentration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MassFlow/UnitsNet.NanoFramework.MassFlow.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MassFlow/UnitsNet.NanoFramework.MassFlow.nuspec index 0bb4fa9b33..a7647773b4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MassFlow/UnitsNet.NanoFramework.MassFlow.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MassFlow/UnitsNet.NanoFramework.MassFlow.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MassFlow - 4.149.0 + 5.0.0-alpha006 Units.NET MassFlow - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component massflow + nanoframework massflow unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MassFlux/UnitsNet.NanoFramework.MassFlux.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MassFlux/UnitsNet.NanoFramework.MassFlux.nuspec index 8cc6c9b394..b827bf7c2f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MassFlux/UnitsNet.NanoFramework.MassFlux.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MassFlux/UnitsNet.NanoFramework.MassFlux.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MassFlux - 4.149.0 + 5.0.0-alpha006 Units.NET MassFlux - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component massflux + nanoframework massflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MassFraction/UnitsNet.NanoFramework.MassFraction.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MassFraction/UnitsNet.NanoFramework.MassFraction.nuspec index 660bf78cc9..239cffb145 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MassFraction/UnitsNet.NanoFramework.MassFraction.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MassFraction/UnitsNet.NanoFramework.MassFraction.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MassFraction - 4.149.0 + 5.0.0-alpha006 Units.NET MassFraction - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component massfraction + nanoframework massfraction unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MassMomentOfInertia/UnitsNet.NanoFramework.MassMomentOfInertia.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MassMomentOfInertia/UnitsNet.NanoFramework.MassMomentOfInertia.nuspec index eb88f33fd2..9892393b2c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MassMomentOfInertia/UnitsNet.NanoFramework.MassMomentOfInertia.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MassMomentOfInertia/UnitsNet.NanoFramework.MassMomentOfInertia.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MassMomentOfInertia - 4.149.0 + 5.0.0-alpha006 Units.NET MassMomentOfInertia - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component massmomentofinertia + nanoframework massmomentofinertia unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MolarEnergy/UnitsNet.NanoFramework.MolarEnergy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MolarEnergy/UnitsNet.NanoFramework.MolarEnergy.nuspec index 6779524b1a..6d66b68146 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MolarEnergy/UnitsNet.NanoFramework.MolarEnergy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MolarEnergy/UnitsNet.NanoFramework.MolarEnergy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MolarEnergy - 4.149.0 + 5.0.0-alpha006 Units.NET MolarEnergy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component molarenergy + nanoframework molarenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MolarEntropy/UnitsNet.NanoFramework.MolarEntropy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MolarEntropy/UnitsNet.NanoFramework.MolarEntropy.nuspec index e5379f2588..981298c1a8 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MolarEntropy/UnitsNet.NanoFramework.MolarEntropy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MolarEntropy/UnitsNet.NanoFramework.MolarEntropy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MolarEntropy - 4.149.0 + 5.0.0-alpha006 Units.NET MolarEntropy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component molarentropy + nanoframework molarentropy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/MolarMass/UnitsNet.NanoFramework.MolarMass.nuspec b/UnitsNet.NanoFramework/GeneratedCode/MolarMass/UnitsNet.NanoFramework.MolarMass.nuspec index fa26ac8190..4782a5ddea 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/MolarMass/UnitsNet.NanoFramework.MolarMass.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/MolarMass/UnitsNet.NanoFramework.MolarMass.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.MolarMass - 4.149.0 + 5.0.0-alpha006 Units.NET MolarMass - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component molarmass + nanoframework molarmass unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Molarity/UnitsNet.NanoFramework.Molarity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Molarity/UnitsNet.NanoFramework.Molarity.nuspec index aafdea14bd..5e2a827c1f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Molarity/UnitsNet.NanoFramework.Molarity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Molarity/UnitsNet.NanoFramework.Molarity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Molarity - 4.149.0 + 5.0.0-alpha006 Units.NET Molarity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component molarity + nanoframework molarity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Permeability/UnitsNet.NanoFramework.Permeability.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Permeability/UnitsNet.NanoFramework.Permeability.nuspec index 64d207b9f6..1fd298d26a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Permeability/UnitsNet.NanoFramework.Permeability.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Permeability/UnitsNet.NanoFramework.Permeability.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Permeability - 4.149.0 + 5.0.0-alpha006 Units.NET Permeability - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component permeability + nanoframework permeability unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Permittivity/UnitsNet.NanoFramework.Permittivity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Permittivity/UnitsNet.NanoFramework.Permittivity.nuspec index dcdc47d399..31229df5f6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Permittivity/UnitsNet.NanoFramework.Permittivity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Permittivity/UnitsNet.NanoFramework.Permittivity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Permittivity - 4.149.0 + 5.0.0-alpha006 Units.NET Permittivity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component permittivity + nanoframework permittivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/PorousMediumPermeability/UnitsNet.NanoFramework.PorousMediumPermeability.nuspec b/UnitsNet.NanoFramework/GeneratedCode/PorousMediumPermeability/UnitsNet.NanoFramework.PorousMediumPermeability.nuspec index df21e806ab..ca1aab9f1c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/PorousMediumPermeability/UnitsNet.NanoFramework.PorousMediumPermeability.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/PorousMediumPermeability/UnitsNet.NanoFramework.PorousMediumPermeability.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.PorousMediumPermeability - 4.149.0 + 5.0.0-alpha006 Units.NET PorousMediumPermeability - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component porousmediumpermeability + nanoframework porousmediumpermeability unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Power/UnitsNet.NanoFramework.Power.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Power/UnitsNet.NanoFramework.Power.nuspec index 6ea81d7038..ef6aa51c71 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Power/UnitsNet.NanoFramework.Power.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Power/UnitsNet.NanoFramework.Power.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Power - 4.149.0 + 5.0.0-alpha006 Units.NET Power - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component power + nanoframework power unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/PowerDensity/UnitsNet.NanoFramework.PowerDensity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/PowerDensity/UnitsNet.NanoFramework.PowerDensity.nuspec index a2e897f6a5..a68fa7305a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/PowerDensity/UnitsNet.NanoFramework.PowerDensity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/PowerDensity/UnitsNet.NanoFramework.PowerDensity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.PowerDensity - 4.149.0 + 5.0.0-alpha006 Units.NET PowerDensity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component powerdensity + nanoframework powerdensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/PowerRatio/UnitsNet.NanoFramework.PowerRatio.nuspec b/UnitsNet.NanoFramework/GeneratedCode/PowerRatio/UnitsNet.NanoFramework.PowerRatio.nuspec index f771544dc1..638365280a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/PowerRatio/UnitsNet.NanoFramework.PowerRatio.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/PowerRatio/UnitsNet.NanoFramework.PowerRatio.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.PowerRatio - 4.149.0 + 5.0.0-alpha006 Units.NET PowerRatio - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component powerratio + nanoframework powerratio unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Pressure/UnitsNet.NanoFramework.Pressure.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Pressure/UnitsNet.NanoFramework.Pressure.nuspec index d2faca1e0b..27334ec9c1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Pressure/UnitsNet.NanoFramework.Pressure.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Pressure/UnitsNet.NanoFramework.Pressure.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Pressure - 4.149.0 + 5.0.0-alpha006 Units.NET Pressure - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component pressure + nanoframework pressure unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/PressureChangeRate/UnitsNet.NanoFramework.PressureChangeRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/PressureChangeRate/UnitsNet.NanoFramework.PressureChangeRate.nuspec index 88afdf438a..4c1bf18e52 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/PressureChangeRate/UnitsNet.NanoFramework.PressureChangeRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/PressureChangeRate/UnitsNet.NanoFramework.PressureChangeRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.PressureChangeRate - 4.149.0 + 5.0.0-alpha006 Units.NET PressureChangeRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component pressurechangerate + nanoframework pressurechangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs b/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs index d676e2f3fe..6f38f65936 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs @@ -47,8 +47,8 @@ // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("4.149.0")] -[assembly: AssemblyFileVersion("4.149.0")] +[assembly: AssemblyVersion("5.0.0")] +[assembly: AssemblyFileVersion("5.0.0")] ////////////////////////////////////////////////// // This assembly doens't require native support // diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Acceleration.g.cs index 002da99fa8..f7f3c04b66 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Acceleration.g.cs @@ -250,79 +250,79 @@ public static Acceleration From(double value, AccelerationUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AccelerationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Acceleration ToUnit(AccelerationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Acceleration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AccelerationUnit.CentimeterPerSecondSquared => (_value) * 1e-2d, - AccelerationUnit.DecimeterPerSecondSquared => (_value) * 1e-1d, - AccelerationUnit.FootPerSecondSquared => _value * 0.304800, - AccelerationUnit.InchPerSecondSquared => _value * 0.0254, - AccelerationUnit.KilometerPerSecondSquared => (_value) * 1e3d, - AccelerationUnit.KnotPerHour => _value * 0.5144444444444 / 3600, - AccelerationUnit.KnotPerMinute => _value * 0.5144444444444 / 60, - AccelerationUnit.KnotPerSecond => _value * 0.5144444444444, - AccelerationUnit.MeterPerSecondSquared => _value, - AccelerationUnit.MicrometerPerSecondSquared => (_value) * 1e-6d, - AccelerationUnit.MillimeterPerSecondSquared => (_value) * 1e-3d, - AccelerationUnit.MillistandardGravity => (_value * 9.80665) * 1e-3d, - AccelerationUnit.NanometerPerSecondSquared => (_value) * 1e-9d, - AccelerationUnit.StandardGravity => _value * 9.80665, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AccelerationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AccelerationUnit.CentimeterPerSecondSquared => (baseUnitValue) / 1e-2d, - AccelerationUnit.DecimeterPerSecondSquared => (baseUnitValue) / 1e-1d, - AccelerationUnit.FootPerSecondSquared => baseUnitValue / 0.304800, - AccelerationUnit.InchPerSecondSquared => baseUnitValue / 0.0254, - AccelerationUnit.KilometerPerSecondSquared => (baseUnitValue) / 1e3d, - AccelerationUnit.KnotPerHour => baseUnitValue / 0.5144444444444 * 3600, - AccelerationUnit.KnotPerMinute => baseUnitValue / 0.5144444444444 * 60, - AccelerationUnit.KnotPerSecond => baseUnitValue / 0.5144444444444, - AccelerationUnit.MeterPerSecondSquared => baseUnitValue, - AccelerationUnit.MicrometerPerSecondSquared => (baseUnitValue) / 1e-6d, - AccelerationUnit.MillimeterPerSecondSquared => (baseUnitValue) / 1e-3d, - AccelerationUnit.MillistandardGravity => (baseUnitValue / 9.80665) / 1e-3d, - AccelerationUnit.NanometerPerSecondSquared => (baseUnitValue) / 1e-9d, - AccelerationUnit.StandardGravity => baseUnitValue / 9.80665, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AccelerationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Acceleration ToUnit(AccelerationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Acceleration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AccelerationUnit.CentimeterPerSecondSquared => (_value) * 1e-2d, + AccelerationUnit.DecimeterPerSecondSquared => (_value) * 1e-1d, + AccelerationUnit.FootPerSecondSquared => _value * 0.304800, + AccelerationUnit.InchPerSecondSquared => _value * 0.0254, + AccelerationUnit.KilometerPerSecondSquared => (_value) * 1e3d, + AccelerationUnit.KnotPerHour => _value * 0.5144444444444 / 3600, + AccelerationUnit.KnotPerMinute => _value * 0.5144444444444 / 60, + AccelerationUnit.KnotPerSecond => _value * 0.5144444444444, + AccelerationUnit.MeterPerSecondSquared => _value, + AccelerationUnit.MicrometerPerSecondSquared => (_value) * 1e-6d, + AccelerationUnit.MillimeterPerSecondSquared => (_value) * 1e-3d, + AccelerationUnit.MillistandardGravity => (_value * 9.80665) * 1e-3d, + AccelerationUnit.NanometerPerSecondSquared => (_value) * 1e-9d, + AccelerationUnit.StandardGravity => _value * 9.80665, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AccelerationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AccelerationUnit.CentimeterPerSecondSquared => (baseUnitValue) / 1e-2d, + AccelerationUnit.DecimeterPerSecondSquared => (baseUnitValue) / 1e-1d, + AccelerationUnit.FootPerSecondSquared => baseUnitValue / 0.304800, + AccelerationUnit.InchPerSecondSquared => baseUnitValue / 0.0254, + AccelerationUnit.KilometerPerSecondSquared => (baseUnitValue) / 1e3d, + AccelerationUnit.KnotPerHour => baseUnitValue / 0.5144444444444 * 3600, + AccelerationUnit.KnotPerMinute => baseUnitValue / 0.5144444444444 * 60, + AccelerationUnit.KnotPerSecond => baseUnitValue / 0.5144444444444, + AccelerationUnit.MeterPerSecondSquared => baseUnitValue, + AccelerationUnit.MicrometerPerSecondSquared => (baseUnitValue) / 1e-6d, + AccelerationUnit.MillimeterPerSecondSquared => (baseUnitValue) / 1e-3d, + AccelerationUnit.MillistandardGravity => (baseUnitValue / 9.80665) / 1e-3d, + AccelerationUnit.NanometerPerSecondSquared => (baseUnitValue) / 1e-9d, + AccelerationUnit.StandardGravity => baseUnitValue / 9.80665, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmountOfSubstance.g.cs index da62df15b7..668cd7bb9c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -261,81 +261,81 @@ public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUni #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmountOfSubstanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new AmountOfSubstance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AmountOfSubstanceUnit.Centimole => (_value) * 1e-2d, - AmountOfSubstanceUnit.CentipoundMole => (_value * 453.59237) * 1e-2d, - AmountOfSubstanceUnit.Decimole => (_value) * 1e-1d, - AmountOfSubstanceUnit.DecipoundMole => (_value * 453.59237) * 1e-1d, - AmountOfSubstanceUnit.Kilomole => (_value) * 1e3d, - AmountOfSubstanceUnit.KilopoundMole => (_value * 453.59237) * 1e3d, - AmountOfSubstanceUnit.Megamole => (_value) * 1e6d, - AmountOfSubstanceUnit.Micromole => (_value) * 1e-6d, - AmountOfSubstanceUnit.MicropoundMole => (_value * 453.59237) * 1e-6d, - AmountOfSubstanceUnit.Millimole => (_value) * 1e-3d, - AmountOfSubstanceUnit.MillipoundMole => (_value * 453.59237) * 1e-3d, - AmountOfSubstanceUnit.Mole => _value, - AmountOfSubstanceUnit.Nanomole => (_value) * 1e-9d, - AmountOfSubstanceUnit.NanopoundMole => (_value * 453.59237) * 1e-9d, - AmountOfSubstanceUnit.PoundMole => _value * 453.59237, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AmountOfSubstanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AmountOfSubstanceUnit.Centimole => (baseUnitValue) / 1e-2d, - AmountOfSubstanceUnit.CentipoundMole => (baseUnitValue / 453.59237) / 1e-2d, - AmountOfSubstanceUnit.Decimole => (baseUnitValue) / 1e-1d, - AmountOfSubstanceUnit.DecipoundMole => (baseUnitValue / 453.59237) / 1e-1d, - AmountOfSubstanceUnit.Kilomole => (baseUnitValue) / 1e3d, - AmountOfSubstanceUnit.KilopoundMole => (baseUnitValue / 453.59237) / 1e3d, - AmountOfSubstanceUnit.Megamole => (baseUnitValue) / 1e6d, - AmountOfSubstanceUnit.Micromole => (baseUnitValue) / 1e-6d, - AmountOfSubstanceUnit.MicropoundMole => (baseUnitValue / 453.59237) / 1e-6d, - AmountOfSubstanceUnit.Millimole => (baseUnitValue) / 1e-3d, - AmountOfSubstanceUnit.MillipoundMole => (baseUnitValue / 453.59237) / 1e-3d, - AmountOfSubstanceUnit.Mole => baseUnitValue, - AmountOfSubstanceUnit.Nanomole => (baseUnitValue) / 1e-9d, - AmountOfSubstanceUnit.NanopoundMole => (baseUnitValue / 453.59237) / 1e-9d, - AmountOfSubstanceUnit.PoundMole => baseUnitValue / 453.59237, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AmountOfSubstanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new AmountOfSubstance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AmountOfSubstanceUnit.Centimole => (_value) * 1e-2d, + AmountOfSubstanceUnit.CentipoundMole => (_value * 453.59237) * 1e-2d, + AmountOfSubstanceUnit.Decimole => (_value) * 1e-1d, + AmountOfSubstanceUnit.DecipoundMole => (_value * 453.59237) * 1e-1d, + AmountOfSubstanceUnit.Kilomole => (_value) * 1e3d, + AmountOfSubstanceUnit.KilopoundMole => (_value * 453.59237) * 1e3d, + AmountOfSubstanceUnit.Megamole => (_value) * 1e6d, + AmountOfSubstanceUnit.Micromole => (_value) * 1e-6d, + AmountOfSubstanceUnit.MicropoundMole => (_value * 453.59237) * 1e-6d, + AmountOfSubstanceUnit.Millimole => (_value) * 1e-3d, + AmountOfSubstanceUnit.MillipoundMole => (_value * 453.59237) * 1e-3d, + AmountOfSubstanceUnit.Mole => _value, + AmountOfSubstanceUnit.Nanomole => (_value) * 1e-9d, + AmountOfSubstanceUnit.NanopoundMole => (_value * 453.59237) * 1e-9d, + AmountOfSubstanceUnit.PoundMole => _value * 453.59237, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AmountOfSubstanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AmountOfSubstanceUnit.Centimole => (baseUnitValue) / 1e-2d, + AmountOfSubstanceUnit.CentipoundMole => (baseUnitValue / 453.59237) / 1e-2d, + AmountOfSubstanceUnit.Decimole => (baseUnitValue) / 1e-1d, + AmountOfSubstanceUnit.DecipoundMole => (baseUnitValue / 453.59237) / 1e-1d, + AmountOfSubstanceUnit.Kilomole => (baseUnitValue) / 1e3d, + AmountOfSubstanceUnit.KilopoundMole => (baseUnitValue / 453.59237) / 1e3d, + AmountOfSubstanceUnit.Megamole => (baseUnitValue) / 1e6d, + AmountOfSubstanceUnit.Micromole => (baseUnitValue) / 1e-6d, + AmountOfSubstanceUnit.MicropoundMole => (baseUnitValue / 453.59237) / 1e-6d, + AmountOfSubstanceUnit.Millimole => (baseUnitValue) / 1e-3d, + AmountOfSubstanceUnit.MillipoundMole => (baseUnitValue / 453.59237) / 1e-3d, + AmountOfSubstanceUnit.Mole => baseUnitValue, + AmountOfSubstanceUnit.Nanomole => (baseUnitValue) / 1e-9d, + AmountOfSubstanceUnit.NanopoundMole => (baseUnitValue / 453.59237) / 1e-9d, + AmountOfSubstanceUnit.PoundMole => baseUnitValue / 453.59237, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 4a13d65242..fea5e888e5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -140,59 +140,59 @@ public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmplitudeRatioUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) - { - var convertedValue = GetValueAs(unit); - return new AmplitudeRatio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AmplitudeRatioUnit.DecibelMicrovolt => _value - 120, - AmplitudeRatioUnit.DecibelMillivolt => _value - 60, - AmplitudeRatioUnit.DecibelUnloaded => _value - 2.218487499, - AmplitudeRatioUnit.DecibelVolt => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AmplitudeRatioUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AmplitudeRatioUnit.DecibelMicrovolt => baseUnitValue + 120, - AmplitudeRatioUnit.DecibelMillivolt => baseUnitValue + 60, - AmplitudeRatioUnit.DecibelUnloaded => baseUnitValue + 2.218487499, - AmplitudeRatioUnit.DecibelVolt => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AmplitudeRatioUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) + { + var convertedValue = GetValueAs(unit); + return new AmplitudeRatio(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AmplitudeRatioUnit.DecibelMicrovolt => _value - 120, + AmplitudeRatioUnit.DecibelMillivolt => _value - 60, + AmplitudeRatioUnit.DecibelUnloaded => _value - 2.218487499, + AmplitudeRatioUnit.DecibelVolt => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AmplitudeRatioUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AmplitudeRatioUnit.DecibelMicrovolt => baseUnitValue + 120, + AmplitudeRatioUnit.DecibelMillivolt => baseUnitValue + 60, + AmplitudeRatioUnit.DecibelUnloaded => baseUnitValue + 2.218487499, + AmplitudeRatioUnit.DecibelVolt => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs index 5be9707d02..1305cad4f6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Angle.g.cs @@ -272,83 +272,83 @@ public static Angle From(double value, AngleUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AngleUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Angle ToUnit(AngleUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Angle(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AngleUnit.Arcminute => _value / 60, - AngleUnit.Arcsecond => _value / 3600, - AngleUnit.Centiradian => (_value * 180 / 3.1415926535897931) * 1e-2d, - AngleUnit.Deciradian => (_value * 180 / 3.1415926535897931) * 1e-1d, - AngleUnit.Degree => _value, - AngleUnit.Gradian => _value * 0.9, - AngleUnit.Microdegree => (_value) * 1e-6d, - AngleUnit.Microradian => (_value * 180 / 3.1415926535897931) * 1e-6d, - AngleUnit.Millidegree => (_value) * 1e-3d, - AngleUnit.Milliradian => (_value * 180 / 3.1415926535897931) * 1e-3d, - AngleUnit.Nanodegree => (_value) * 1e-9d, - AngleUnit.Nanoradian => (_value * 180 / 3.1415926535897931) * 1e-9d, - AngleUnit.NatoMil => _value * 9 / 160, - AngleUnit.Radian => _value * 180 / 3.1415926535897931, - AngleUnit.Revolution => _value * 360, - AngleUnit.Tilt => Math.Asin(_value) * 180 / 3.1415926535897931, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AngleUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AngleUnit.Arcminute => baseUnitValue * 60, - AngleUnit.Arcsecond => baseUnitValue * 3600, - AngleUnit.Centiradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-2d, - AngleUnit.Deciradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-1d, - AngleUnit.Degree => baseUnitValue, - AngleUnit.Gradian => baseUnitValue / 0.9, - AngleUnit.Microdegree => (baseUnitValue) / 1e-6d, - AngleUnit.Microradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-6d, - AngleUnit.Millidegree => (baseUnitValue) / 1e-3d, - AngleUnit.Milliradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-3d, - AngleUnit.Nanodegree => (baseUnitValue) / 1e-9d, - AngleUnit.Nanoradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-9d, - AngleUnit.NatoMil => baseUnitValue * 160 / 9, - AngleUnit.Radian => baseUnitValue / 180 * 3.1415926535897931, - AngleUnit.Revolution => baseUnitValue / 360, - AngleUnit.Tilt => Math.Sin(baseUnitValue / 180 * 3.1415926535897931), - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AngleUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Angle ToUnit(AngleUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Angle(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AngleUnit.Arcminute => _value / 60, + AngleUnit.Arcsecond => _value / 3600, + AngleUnit.Centiradian => (_value * 180 / 3.1415926535897931) * 1e-2d, + AngleUnit.Deciradian => (_value * 180 / 3.1415926535897931) * 1e-1d, + AngleUnit.Degree => _value, + AngleUnit.Gradian => _value * 0.9, + AngleUnit.Microdegree => (_value) * 1e-6d, + AngleUnit.Microradian => (_value * 180 / 3.1415926535897931) * 1e-6d, + AngleUnit.Millidegree => (_value) * 1e-3d, + AngleUnit.Milliradian => (_value * 180 / 3.1415926535897931) * 1e-3d, + AngleUnit.Nanodegree => (_value) * 1e-9d, + AngleUnit.Nanoradian => (_value * 180 / 3.1415926535897931) * 1e-9d, + AngleUnit.NatoMil => _value * 9 / 160, + AngleUnit.Radian => _value * 180 / 3.1415926535897931, + AngleUnit.Revolution => _value * 360, + AngleUnit.Tilt => Math.Asin(_value) * 180 / 3.1415926535897931, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AngleUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AngleUnit.Arcminute => baseUnitValue * 60, + AngleUnit.Arcsecond => baseUnitValue * 3600, + AngleUnit.Centiradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-2d, + AngleUnit.Deciradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-1d, + AngleUnit.Degree => baseUnitValue, + AngleUnit.Gradian => baseUnitValue / 0.9, + AngleUnit.Microdegree => (baseUnitValue) / 1e-6d, + AngleUnit.Microradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-6d, + AngleUnit.Millidegree => (baseUnitValue) / 1e-3d, + AngleUnit.Milliradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-3d, + AngleUnit.Nanodegree => (baseUnitValue) / 1e-9d, + AngleUnit.Nanoradian => (baseUnitValue / 180 * 3.1415926535897931) / 1e-9d, + AngleUnit.NatoMil => baseUnitValue * 160 / 9, + AngleUnit.Radian => baseUnitValue / 180 * 3.1415926535897931, + AngleUnit.Revolution => baseUnitValue / 360, + AngleUnit.Tilt => Math.Sin(baseUnitValue / 180 * 3.1415926535897931), + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentEnergy.g.cs index 97411b3469..05787e8436 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentEnergy.g.cs @@ -129,57 +129,57 @@ public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentEnergyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ApparentEnergy ToUnit(ApparentEnergyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ApparentEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ApparentEnergyUnit.KilovoltampereHour => (_value) * 1e3d, - ApparentEnergyUnit.MegavoltampereHour => (_value) * 1e6d, - ApparentEnergyUnit.VoltampereHour => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ApparentEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ApparentEnergyUnit.KilovoltampereHour => (baseUnitValue) / 1e3d, - ApparentEnergyUnit.MegavoltampereHour => (baseUnitValue) / 1e6d, - ApparentEnergyUnit.VoltampereHour => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ApparentEnergyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ApparentEnergy ToUnit(ApparentEnergyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ApparentEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ApparentEnergyUnit.KilovoltampereHour => (_value) * 1e3d, + ApparentEnergyUnit.MegavoltampereHour => (_value) * 1e6d, + ApparentEnergyUnit.VoltampereHour => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ApparentEnergyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ApparentEnergyUnit.KilovoltampereHour => (baseUnitValue) / 1e3d, + ApparentEnergyUnit.MegavoltampereHour => (baseUnitValue) / 1e6d, + ApparentEnergyUnit.VoltampereHour => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentPower.g.cs index 3364b050bb..f2573fe8f7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentPower.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ApparentPower.g.cs @@ -140,59 +140,59 @@ public static ApparentPower From(double value, ApparentPowerUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentPowerUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ApparentPower ToUnit(ApparentPowerUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ApparentPower(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ApparentPowerUnit.Gigavoltampere => (_value) * 1e9d, - ApparentPowerUnit.Kilovoltampere => (_value) * 1e3d, - ApparentPowerUnit.Megavoltampere => (_value) * 1e6d, - ApparentPowerUnit.Voltampere => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ApparentPowerUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ApparentPowerUnit.Gigavoltampere => (baseUnitValue) / 1e9d, - ApparentPowerUnit.Kilovoltampere => (baseUnitValue) / 1e3d, - ApparentPowerUnit.Megavoltampere => (baseUnitValue) / 1e6d, - ApparentPowerUnit.Voltampere => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ApparentPowerUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ApparentPower ToUnit(ApparentPowerUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ApparentPower(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ApparentPowerUnit.Gigavoltampere => (_value) * 1e9d, + ApparentPowerUnit.Kilovoltampere => (_value) * 1e3d, + ApparentPowerUnit.Megavoltampere => (_value) * 1e6d, + ApparentPowerUnit.Voltampere => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ApparentPowerUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ApparentPowerUnit.Gigavoltampere => (baseUnitValue) / 1e9d, + ApparentPowerUnit.Kilovoltampere => (baseUnitValue) / 1e3d, + ApparentPowerUnit.Megavoltampere => (baseUnitValue) / 1e6d, + ApparentPowerUnit.Voltampere => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Area.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Area.g.cs index 0a1b8986cf..83a78cf638 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Area.g.cs @@ -250,79 +250,79 @@ public static Area From(double value, AreaUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Area ToUnit(AreaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Area(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AreaUnit.Acre => _value * 4046.85642, - AreaUnit.Hectare => _value * 1e4, - AreaUnit.SquareCentimeter => _value * 1e-4, - AreaUnit.SquareDecimeter => _value * 1e-2, - AreaUnit.SquareFoot => _value * 9.290304e-2, - AreaUnit.SquareInch => _value * 0.00064516, - AreaUnit.SquareKilometer => _value * 1e6, - AreaUnit.SquareMeter => _value, - AreaUnit.SquareMicrometer => _value * 1e-12, - AreaUnit.SquareMile => _value * 2.59e6, - AreaUnit.SquareMillimeter => _value * 1e-6, - AreaUnit.SquareNauticalMile => _value * 3429904, - AreaUnit.SquareYard => _value * 0.836127, - AreaUnit.UsSurveySquareFoot => _value * 0.09290341161, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AreaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AreaUnit.Acre => baseUnitValue / 4046.85642, - AreaUnit.Hectare => baseUnitValue / 1e4, - AreaUnit.SquareCentimeter => baseUnitValue / 1e-4, - AreaUnit.SquareDecimeter => baseUnitValue / 1e-2, - AreaUnit.SquareFoot => baseUnitValue / 9.290304e-2, - AreaUnit.SquareInch => baseUnitValue / 0.00064516, - AreaUnit.SquareKilometer => baseUnitValue / 1e6, - AreaUnit.SquareMeter => baseUnitValue, - AreaUnit.SquareMicrometer => baseUnitValue / 1e-12, - AreaUnit.SquareMile => baseUnitValue / 2.59e6, - AreaUnit.SquareMillimeter => baseUnitValue / 1e-6, - AreaUnit.SquareNauticalMile => baseUnitValue / 3429904, - AreaUnit.SquareYard => baseUnitValue / 0.836127, - AreaUnit.UsSurveySquareFoot => baseUnitValue / 0.09290341161, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Area ToUnit(AreaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Area(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AreaUnit.Acre => _value * 4046.85642, + AreaUnit.Hectare => _value * 1e4, + AreaUnit.SquareCentimeter => _value * 1e-4, + AreaUnit.SquareDecimeter => _value * 1e-2, + AreaUnit.SquareFoot => _value * 9.290304e-2, + AreaUnit.SquareInch => _value * 0.00064516, + AreaUnit.SquareKilometer => _value * 1e6, + AreaUnit.SquareMeter => _value, + AreaUnit.SquareMicrometer => _value * 1e-12, + AreaUnit.SquareMile => _value * 2.59e6, + AreaUnit.SquareMillimeter => _value * 1e-6, + AreaUnit.SquareNauticalMile => _value * 3429904, + AreaUnit.SquareYard => _value * 0.836127, + AreaUnit.UsSurveySquareFoot => _value * 0.09290341161, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AreaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AreaUnit.Acre => baseUnitValue / 4046.85642, + AreaUnit.Hectare => baseUnitValue / 1e4, + AreaUnit.SquareCentimeter => baseUnitValue / 1e-4, + AreaUnit.SquareDecimeter => baseUnitValue / 1e-2, + AreaUnit.SquareFoot => baseUnitValue / 9.290304e-2, + AreaUnit.SquareInch => baseUnitValue / 0.00064516, + AreaUnit.SquareKilometer => baseUnitValue / 1e6, + AreaUnit.SquareMeter => baseUnitValue, + AreaUnit.SquareMicrometer => baseUnitValue / 1e-12, + AreaUnit.SquareMile => baseUnitValue / 2.59e6, + AreaUnit.SquareMillimeter => baseUnitValue / 1e-6, + AreaUnit.SquareNauticalMile => baseUnitValue / 3429904, + AreaUnit.SquareYard => baseUnitValue / 0.836127, + AreaUnit.UsSurveySquareFoot => baseUnitValue / 0.09290341161, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaDensity.g.cs index 6809894507..1d52c11c99 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaDensity.g.cs @@ -129,57 +129,57 @@ public static AreaDensity From(double value, AreaDensityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public AreaDensity ToUnit(AreaDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new AreaDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AreaDensityUnit.GramPerSquareMeter => _value / 1000, - AreaDensityUnit.KilogramPerSquareMeter => _value, - AreaDensityUnit.MilligramPerSquareMeter => _value / 1000000, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AreaDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AreaDensityUnit.GramPerSquareMeter => baseUnitValue * 1000, - AreaDensityUnit.KilogramPerSquareMeter => baseUnitValue, - AreaDensityUnit.MilligramPerSquareMeter => baseUnitValue * 1000000, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public AreaDensity ToUnit(AreaDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new AreaDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AreaDensityUnit.GramPerSquareMeter => _value / 1000, + AreaDensityUnit.KilogramPerSquareMeter => _value, + AreaDensityUnit.MilligramPerSquareMeter => _value / 1000000, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AreaDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AreaDensityUnit.GramPerSquareMeter => baseUnitValue * 1000, + AreaDensityUnit.KilogramPerSquareMeter => baseUnitValue, + AreaDensityUnit.MilligramPerSquareMeter => baseUnitValue * 1000000, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index 3f208aab52..9cf1263d21 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -162,63 +162,63 @@ public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaMomentOfInertiaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new AreaMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - AreaMomentOfInertiaUnit.CentimeterToTheFourth => _value / 1e8, - AreaMomentOfInertiaUnit.DecimeterToTheFourth => _value / 1e4, - AreaMomentOfInertiaUnit.FootToTheFourth => _value * 0.0086309748412416, - AreaMomentOfInertiaUnit.InchToTheFourth => _value * 0.0000004162314256, - AreaMomentOfInertiaUnit.MeterToTheFourth => _value, - AreaMomentOfInertiaUnit.MillimeterToTheFourth => _value / 1e12, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(AreaMomentOfInertiaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - AreaMomentOfInertiaUnit.CentimeterToTheFourth => baseUnitValue * 1e8, - AreaMomentOfInertiaUnit.DecimeterToTheFourth => baseUnitValue * 1e4, - AreaMomentOfInertiaUnit.FootToTheFourth => baseUnitValue / 0.0086309748412416, - AreaMomentOfInertiaUnit.InchToTheFourth => baseUnitValue / 0.0000004162314256, - AreaMomentOfInertiaUnit.MeterToTheFourth => baseUnitValue, - AreaMomentOfInertiaUnit.MillimeterToTheFourth => baseUnitValue * 1e12, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(AreaMomentOfInertiaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new AreaMomentOfInertia(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + AreaMomentOfInertiaUnit.CentimeterToTheFourth => _value / 1e8, + AreaMomentOfInertiaUnit.DecimeterToTheFourth => _value / 1e4, + AreaMomentOfInertiaUnit.FootToTheFourth => _value * 0.0086309748412416, + AreaMomentOfInertiaUnit.InchToTheFourth => _value * 0.0000004162314256, + AreaMomentOfInertiaUnit.MeterToTheFourth => _value, + AreaMomentOfInertiaUnit.MillimeterToTheFourth => _value / 1e12, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(AreaMomentOfInertiaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + AreaMomentOfInertiaUnit.CentimeterToTheFourth => baseUnitValue * 1e8, + AreaMomentOfInertiaUnit.DecimeterToTheFourth => baseUnitValue * 1e4, + AreaMomentOfInertiaUnit.FootToTheFourth => baseUnitValue / 0.0086309748412416, + AreaMomentOfInertiaUnit.InchToTheFourth => baseUnitValue / 0.0000004162314256, + AreaMomentOfInertiaUnit.MeterToTheFourth => baseUnitValue, + AreaMomentOfInertiaUnit.MillimeterToTheFourth => baseUnitValue * 1e12, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/BitRate.g.cs index 71f10290b1..3612a18ed6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/BitRate.g.cs @@ -385,103 +385,103 @@ public static BitRate From(double value, BitRateUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BitRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public BitRate ToUnit(BitRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new BitRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - BitRateUnit.BitPerSecond => _value, - BitRateUnit.BytePerSecond => _value * 8d, - BitRateUnit.ExabitPerSecond => (_value) * 1e18d, - BitRateUnit.ExabytePerSecond => (_value * 8d) * 1e18d, - BitRateUnit.ExbibitPerSecond => (_value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - BitRateUnit.ExbibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - BitRateUnit.GibibitPerSecond => (_value) * (1024d * 1024 * 1024), - BitRateUnit.GibibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024), - BitRateUnit.GigabitPerSecond => (_value) * 1e9d, - BitRateUnit.GigabytePerSecond => (_value * 8d) * 1e9d, - BitRateUnit.KibibitPerSecond => (_value) * 1024d, - BitRateUnit.KibibytePerSecond => (_value * 8d) * 1024d, - BitRateUnit.KilobitPerSecond => (_value) * 1e3d, - BitRateUnit.KilobytePerSecond => (_value * 8d) * 1e3d, - BitRateUnit.MebibitPerSecond => (_value) * (1024d * 1024), - BitRateUnit.MebibytePerSecond => (_value * 8d) * (1024d * 1024), - BitRateUnit.MegabitPerSecond => (_value) * 1e6d, - BitRateUnit.MegabytePerSecond => (_value * 8d) * 1e6d, - BitRateUnit.PebibitPerSecond => (_value) * (1024d * 1024 * 1024 * 1024 * 1024), - BitRateUnit.PebibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024), - BitRateUnit.PetabitPerSecond => (_value) * 1e15d, - BitRateUnit.PetabytePerSecond => (_value * 8d) * 1e15d, - BitRateUnit.TebibitPerSecond => (_value) * (1024d * 1024 * 1024 * 1024), - BitRateUnit.TebibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024 * 1024), - BitRateUnit.TerabitPerSecond => (_value) * 1e12d, - BitRateUnit.TerabytePerSecond => (_value * 8d) * 1e12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(BitRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - BitRateUnit.BitPerSecond => baseUnitValue, - BitRateUnit.BytePerSecond => baseUnitValue / 8d, - BitRateUnit.ExabitPerSecond => (baseUnitValue) / 1e18d, - BitRateUnit.ExabytePerSecond => (baseUnitValue / 8d) / 1e18d, - BitRateUnit.ExbibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - BitRateUnit.ExbibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - BitRateUnit.GibibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024), - BitRateUnit.GibibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024), - BitRateUnit.GigabitPerSecond => (baseUnitValue) / 1e9d, - BitRateUnit.GigabytePerSecond => (baseUnitValue / 8d) / 1e9d, - BitRateUnit.KibibitPerSecond => (baseUnitValue) / 1024d, - BitRateUnit.KibibytePerSecond => (baseUnitValue / 8d) / 1024d, - BitRateUnit.KilobitPerSecond => (baseUnitValue) / 1e3d, - BitRateUnit.KilobytePerSecond => (baseUnitValue / 8d) / 1e3d, - BitRateUnit.MebibitPerSecond => (baseUnitValue) / (1024d * 1024), - BitRateUnit.MebibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024), - BitRateUnit.MegabitPerSecond => (baseUnitValue) / 1e6d, - BitRateUnit.MegabytePerSecond => (baseUnitValue / 8d) / 1e6d, - BitRateUnit.PebibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024), - BitRateUnit.PebibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024), - BitRateUnit.PetabitPerSecond => (baseUnitValue) / 1e15d, - BitRateUnit.PetabytePerSecond => (baseUnitValue / 8d) / 1e15d, - BitRateUnit.TebibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024 * 1024), - BitRateUnit.TebibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024), - BitRateUnit.TerabitPerSecond => (baseUnitValue) / 1e12d, - BitRateUnit.TerabytePerSecond => (baseUnitValue / 8d) / 1e12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(BitRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public BitRate ToUnit(BitRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new BitRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + BitRateUnit.BitPerSecond => _value, + BitRateUnit.BytePerSecond => _value * 8d, + BitRateUnit.ExabitPerSecond => (_value) * 1e18d, + BitRateUnit.ExabytePerSecond => (_value * 8d) * 1e18d, + BitRateUnit.ExbibitPerSecond => (_value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + BitRateUnit.ExbibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + BitRateUnit.GibibitPerSecond => (_value) * (1024d * 1024 * 1024), + BitRateUnit.GibibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024), + BitRateUnit.GigabitPerSecond => (_value) * 1e9d, + BitRateUnit.GigabytePerSecond => (_value * 8d) * 1e9d, + BitRateUnit.KibibitPerSecond => (_value) * 1024d, + BitRateUnit.KibibytePerSecond => (_value * 8d) * 1024d, + BitRateUnit.KilobitPerSecond => (_value) * 1e3d, + BitRateUnit.KilobytePerSecond => (_value * 8d) * 1e3d, + BitRateUnit.MebibitPerSecond => (_value) * (1024d * 1024), + BitRateUnit.MebibytePerSecond => (_value * 8d) * (1024d * 1024), + BitRateUnit.MegabitPerSecond => (_value) * 1e6d, + BitRateUnit.MegabytePerSecond => (_value * 8d) * 1e6d, + BitRateUnit.PebibitPerSecond => (_value) * (1024d * 1024 * 1024 * 1024 * 1024), + BitRateUnit.PebibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024), + BitRateUnit.PetabitPerSecond => (_value) * 1e15d, + BitRateUnit.PetabytePerSecond => (_value * 8d) * 1e15d, + BitRateUnit.TebibitPerSecond => (_value) * (1024d * 1024 * 1024 * 1024), + BitRateUnit.TebibytePerSecond => (_value * 8d) * (1024d * 1024 * 1024 * 1024), + BitRateUnit.TerabitPerSecond => (_value) * 1e12d, + BitRateUnit.TerabytePerSecond => (_value * 8d) * 1e12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(BitRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + BitRateUnit.BitPerSecond => baseUnitValue, + BitRateUnit.BytePerSecond => baseUnitValue / 8d, + BitRateUnit.ExabitPerSecond => (baseUnitValue) / 1e18d, + BitRateUnit.ExabytePerSecond => (baseUnitValue / 8d) / 1e18d, + BitRateUnit.ExbibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + BitRateUnit.ExbibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + BitRateUnit.GibibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024), + BitRateUnit.GibibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024), + BitRateUnit.GigabitPerSecond => (baseUnitValue) / 1e9d, + BitRateUnit.GigabytePerSecond => (baseUnitValue / 8d) / 1e9d, + BitRateUnit.KibibitPerSecond => (baseUnitValue) / 1024d, + BitRateUnit.KibibytePerSecond => (baseUnitValue / 8d) / 1024d, + BitRateUnit.KilobitPerSecond => (baseUnitValue) / 1e3d, + BitRateUnit.KilobytePerSecond => (baseUnitValue / 8d) / 1e3d, + BitRateUnit.MebibitPerSecond => (baseUnitValue) / (1024d * 1024), + BitRateUnit.MebibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024), + BitRateUnit.MegabitPerSecond => (baseUnitValue) / 1e6d, + BitRateUnit.MegabytePerSecond => (baseUnitValue / 8d) / 1e6d, + BitRateUnit.PebibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024), + BitRateUnit.PebibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024), + BitRateUnit.PetabitPerSecond => (baseUnitValue) / 1e15d, + BitRateUnit.PetabytePerSecond => (baseUnitValue / 8d) / 1e15d, + BitRateUnit.TebibitPerSecond => (baseUnitValue) / (1024d * 1024 * 1024 * 1024), + BitRateUnit.TebibytePerSecond => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024), + BitRateUnit.TerabitPerSecond => (baseUnitValue) / 1e12d, + BitRateUnit.TerabytePerSecond => (baseUnitValue / 8d) / 1e12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 5c29a4782f..f8a585aa89 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -129,57 +129,57 @@ public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelC #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BrakeSpecificFuelConsumptionUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) - { - var convertedValue = GetValueAs(unit); - return new BrakeSpecificFuelConsumption(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour => _value / 3.6e9, - BrakeSpecificFuelConsumptionUnit.KilogramPerJoule => _value, - BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour => _value * 1.689659410672e-7, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(BrakeSpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour => baseUnitValue * 3.6e9, - BrakeSpecificFuelConsumptionUnit.KilogramPerJoule => baseUnitValue, - BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour => baseUnitValue / 1.689659410672e-7, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(BrakeSpecificFuelConsumptionUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) + { + var convertedValue = GetValueAs(unit); + return new BrakeSpecificFuelConsumption(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour => _value / 3.6e9, + BrakeSpecificFuelConsumptionUnit.KilogramPerJoule => _value, + BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour => _value * 1.689659410672e-7, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(BrakeSpecificFuelConsumptionUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour => baseUnitValue * 3.6e9, + BrakeSpecificFuelConsumptionUnit.KilogramPerJoule => baseUnitValue, + BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour => baseUnitValue / 1.689659410672e-7, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Capacitance.g.cs index 8b1723421b..6a749fd92c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Capacitance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Capacitance.g.cs @@ -176,65 +176,65 @@ public static Capacitance From(double value, CapacitanceUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CapacitanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Capacitance ToUnit(CapacitanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Capacitance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - CapacitanceUnit.Farad => _value, - CapacitanceUnit.Kilofarad => (_value) * 1e3d, - CapacitanceUnit.Megafarad => (_value) * 1e6d, - CapacitanceUnit.Microfarad => (_value) * 1e-6d, - CapacitanceUnit.Millifarad => (_value) * 1e-3d, - CapacitanceUnit.Nanofarad => (_value) * 1e-9d, - CapacitanceUnit.Picofarad => (_value) * 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(CapacitanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - CapacitanceUnit.Farad => baseUnitValue, - CapacitanceUnit.Kilofarad => (baseUnitValue) / 1e3d, - CapacitanceUnit.Megafarad => (baseUnitValue) / 1e6d, - CapacitanceUnit.Microfarad => (baseUnitValue) / 1e-6d, - CapacitanceUnit.Millifarad => (baseUnitValue) / 1e-3d, - CapacitanceUnit.Nanofarad => (baseUnitValue) / 1e-9d, - CapacitanceUnit.Picofarad => (baseUnitValue) / 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CapacitanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Capacitance ToUnit(CapacitanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Capacitance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + CapacitanceUnit.Farad => _value, + CapacitanceUnit.Kilofarad => (_value) * 1e3d, + CapacitanceUnit.Megafarad => (_value) * 1e6d, + CapacitanceUnit.Microfarad => (_value) * 1e-6d, + CapacitanceUnit.Millifarad => (_value) * 1e-3d, + CapacitanceUnit.Nanofarad => (_value) * 1e-9d, + CapacitanceUnit.Picofarad => (_value) * 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(CapacitanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + CapacitanceUnit.Farad => baseUnitValue, + CapacitanceUnit.Kilofarad => (baseUnitValue) / 1e3d, + CapacitanceUnit.Megafarad => (baseUnitValue) / 1e6d, + CapacitanceUnit.Microfarad => (baseUnitValue) / 1e-6d, + CapacitanceUnit.Millifarad => (baseUnitValue) / 1e-3d, + CapacitanceUnit.Nanofarad => (baseUnitValue) / 1e-9d, + CapacitanceUnit.Picofarad => (baseUnitValue) / 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index 0b23d9a7b6..1937eb1181 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -129,57 +129,57 @@ public static CoefficientOfThermalExpansion From(double value, CoefficientOfTher #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CoefficientOfThermalExpansionUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) - { - var convertedValue = GetValueAs(unit); - return new CoefficientOfThermalExpansion(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - CoefficientOfThermalExpansionUnit.InverseDegreeCelsius => _value, - CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit => _value * 9 / 5, - CoefficientOfThermalExpansionUnit.InverseKelvin => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(CoefficientOfThermalExpansionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - CoefficientOfThermalExpansionUnit.InverseDegreeCelsius => baseUnitValue, - CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit => baseUnitValue * 5 / 9, - CoefficientOfThermalExpansionUnit.InverseKelvin => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CoefficientOfThermalExpansionUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) + { + var convertedValue = GetValueAs(unit); + return new CoefficientOfThermalExpansion(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + CoefficientOfThermalExpansionUnit.InverseDegreeCelsius => _value, + CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit => _value * 9 / 5, + CoefficientOfThermalExpansionUnit.InverseKelvin => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(CoefficientOfThermalExpansionUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + CoefficientOfThermalExpansionUnit.InverseDegreeCelsius => baseUnitValue, + CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit => baseUnitValue * 5 / 9, + CoefficientOfThermalExpansionUnit.InverseKelvin => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Compressibility.g.cs index e92522ef3f..ba7ec0364e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Compressibility.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Compressibility.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// Compressibility is the measure of the relative volume change of a fluid or solid in response to pressure changes. + /// /// public struct Compressibility { @@ -173,65 +173,65 @@ public static Compressibility From(double value, CompressibilityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CompressibilityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Compressibility ToUnit(CompressibilityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Compressibility(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - CompressibilityUnit.InverseAtmosphere => _value * 101325, - CompressibilityUnit.InverseBar => _value * 1e5, - CompressibilityUnit.InverseKilopascal => _value * 1e3, - CompressibilityUnit.InverseMegapascal => _value * 1e6, - CompressibilityUnit.InverseMillibar => _value * 100, - CompressibilityUnit.InversePascal => _value, - CompressibilityUnit.InversePoundForcePerSquareInch => _value * 6.894757293168361e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(CompressibilityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - CompressibilityUnit.InverseAtmosphere => baseUnitValue / 101325, - CompressibilityUnit.InverseBar => baseUnitValue / 1e5, - CompressibilityUnit.InverseKilopascal => baseUnitValue / 1e3, - CompressibilityUnit.InverseMegapascal => baseUnitValue / 1e6, - CompressibilityUnit.InverseMillibar => baseUnitValue / 100, - CompressibilityUnit.InversePascal => baseUnitValue, - CompressibilityUnit.InversePoundForcePerSquareInch => baseUnitValue / 6.894757293168361e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(CompressibilityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Compressibility ToUnit(CompressibilityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Compressibility(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + CompressibilityUnit.InverseAtmosphere => _value * 101325, + CompressibilityUnit.InverseBar => _value * 1e5, + CompressibilityUnit.InverseKilopascal => _value * 1e3, + CompressibilityUnit.InverseMegapascal => _value * 1e6, + CompressibilityUnit.InverseMillibar => _value * 100, + CompressibilityUnit.InversePascal => _value, + CompressibilityUnit.InversePoundForcePerSquareInch => _value * 6.894757293168361e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(CompressibilityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + CompressibilityUnit.InverseAtmosphere => baseUnitValue / 101325, + CompressibilityUnit.InverseBar => baseUnitValue / 1e5, + CompressibilityUnit.InverseKilopascal => baseUnitValue / 1e3, + CompressibilityUnit.InverseMegapascal => baseUnitValue / 1e6, + CompressibilityUnit.InverseMillibar => baseUnitValue / 100, + CompressibilityUnit.InversePascal => baseUnitValue, + CompressibilityUnit.InversePoundForcePerSquareInch => baseUnitValue / 6.894757293168361e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Density.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Density.g.cs index 96c040a12e..552c710f9c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Density.g.cs @@ -660,153 +660,153 @@ public static Density From(double value, DensityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Density ToUnit(DensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Density(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - DensityUnit.CentigramPerDeciliter => (_value / 1e-1) * 1e-2d, - DensityUnit.CentigramPerLiter => (_value / 1) * 1e-2d, - DensityUnit.CentigramPerMilliliter => (_value / 1e-3) * 1e-2d, - DensityUnit.DecigramPerDeciliter => (_value / 1e-1) * 1e-1d, - DensityUnit.DecigramPerLiter => (_value / 1) * 1e-1d, - DensityUnit.DecigramPerMilliliter => (_value / 1e-3) * 1e-1d, - DensityUnit.GramPerCubicCentimeter => _value / 1e-3, - DensityUnit.GramPerCubicFoot => _value * 0.0353146667214886, - DensityUnit.GramPerCubicInch => _value * 61.0237440947323, - DensityUnit.GramPerCubicMeter => _value / 1e3, - DensityUnit.GramPerCubicMillimeter => _value / 1e-6, - DensityUnit.GramPerDeciliter => _value / 1e-1, - DensityUnit.GramPerLiter => _value / 1, - DensityUnit.GramPerMilliliter => _value / 1e-3, - DensityUnit.KilogramPerCubicCentimeter => (_value / 1e-3) * 1e3d, - DensityUnit.KilogramPerCubicMeter => (_value / 1e3) * 1e3d, - DensityUnit.KilogramPerCubicMillimeter => (_value / 1e-6) * 1e3d, - DensityUnit.KilogramPerLiter => _value * 1e3, - DensityUnit.KilopoundPerCubicFoot => (_value / 0.062427961) * 1e3d, - DensityUnit.KilopoundPerCubicInch => (_value / 3.6127298147753e-5) * 1e3d, - DensityUnit.MicrogramPerCubicMeter => (_value / 1e3) * 1e-6d, - DensityUnit.MicrogramPerDeciliter => (_value / 1e-1) * 1e-6d, - DensityUnit.MicrogramPerLiter => (_value / 1) * 1e-6d, - DensityUnit.MicrogramPerMilliliter => (_value / 1e-3) * 1e-6d, - DensityUnit.MilligramPerCubicMeter => (_value / 1e3) * 1e-3d, - DensityUnit.MilligramPerDeciliter => (_value / 1e-1) * 1e-3d, - DensityUnit.MilligramPerLiter => (_value / 1) * 1e-3d, - DensityUnit.MilligramPerMilliliter => (_value / 1e-3) * 1e-3d, - DensityUnit.NanogramPerDeciliter => (_value / 1e-1) * 1e-9d, - DensityUnit.NanogramPerLiter => (_value / 1) * 1e-9d, - DensityUnit.NanogramPerMilliliter => (_value / 1e-3) * 1e-9d, - DensityUnit.PicogramPerDeciliter => (_value / 1e-1) * 1e-12d, - DensityUnit.PicogramPerLiter => (_value / 1) * 1e-12d, - DensityUnit.PicogramPerMilliliter => (_value / 1e-3) * 1e-12d, - DensityUnit.PoundPerCubicCentimeter => _value / 2.204622621848775e-6, - DensityUnit.PoundPerCubicFoot => _value / 0.062427961, - DensityUnit.PoundPerCubicInch => _value / 3.6127298147753e-5, - DensityUnit.PoundPerCubicMeter => _value / 2.204622621848775, - DensityUnit.PoundPerCubicMillimeter => _value / 2.204622621848775e-9, - DensityUnit.PoundPerImperialGallon => _value * 9.9776398e1, - DensityUnit.PoundPerUSGallon => _value * 1.19826427e2, - DensityUnit.SlugPerCubicCentimeter => _value * 14593903, - DensityUnit.SlugPerCubicFoot => _value * 515.378818, - DensityUnit.SlugPerCubicInch => _value * 890574.60201535, - DensityUnit.SlugPerCubicMeter => _value * 14.5939, - DensityUnit.SlugPerCubicMillimeter => _value * 14593903000, - DensityUnit.TonnePerCubicCentimeter => _value / 1e-9, - DensityUnit.TonnePerCubicFoot => _value * 3.53146667214886e4, - DensityUnit.TonnePerCubicInch => _value * 6.10237440947323e7, - DensityUnit.TonnePerCubicMeter => _value / 0.001, - DensityUnit.TonnePerCubicMillimeter => _value / 1e-12, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(DensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - DensityUnit.CentigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-2d, - DensityUnit.CentigramPerLiter => (baseUnitValue * 1) / 1e-2d, - DensityUnit.CentigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-2d, - DensityUnit.DecigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-1d, - DensityUnit.DecigramPerLiter => (baseUnitValue * 1) / 1e-1d, - DensityUnit.DecigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-1d, - DensityUnit.GramPerCubicCentimeter => baseUnitValue * 1e-3, - DensityUnit.GramPerCubicFoot => baseUnitValue / 0.0353146667214886, - DensityUnit.GramPerCubicInch => baseUnitValue / 61.0237440947323, - DensityUnit.GramPerCubicMeter => baseUnitValue * 1e3, - DensityUnit.GramPerCubicMillimeter => baseUnitValue * 1e-6, - DensityUnit.GramPerDeciliter => baseUnitValue * 1e-1, - DensityUnit.GramPerLiter => baseUnitValue * 1, - DensityUnit.GramPerMilliliter => baseUnitValue * 1e-3, - DensityUnit.KilogramPerCubicCentimeter => (baseUnitValue * 1e-3) / 1e3d, - DensityUnit.KilogramPerCubicMeter => (baseUnitValue * 1e3) / 1e3d, - DensityUnit.KilogramPerCubicMillimeter => (baseUnitValue * 1e-6) / 1e3d, - DensityUnit.KilogramPerLiter => baseUnitValue / 1e3, - DensityUnit.KilopoundPerCubicFoot => (baseUnitValue * 0.062427961) / 1e3d, - DensityUnit.KilopoundPerCubicInch => (baseUnitValue * 3.6127298147753e-5) / 1e3d, - DensityUnit.MicrogramPerCubicMeter => (baseUnitValue * 1e3) / 1e-6d, - DensityUnit.MicrogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-6d, - DensityUnit.MicrogramPerLiter => (baseUnitValue * 1) / 1e-6d, - DensityUnit.MicrogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-6d, - DensityUnit.MilligramPerCubicMeter => (baseUnitValue * 1e3) / 1e-3d, - DensityUnit.MilligramPerDeciliter => (baseUnitValue * 1e-1) / 1e-3d, - DensityUnit.MilligramPerLiter => (baseUnitValue * 1) / 1e-3d, - DensityUnit.MilligramPerMilliliter => (baseUnitValue * 1e-3) / 1e-3d, - DensityUnit.NanogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-9d, - DensityUnit.NanogramPerLiter => (baseUnitValue * 1) / 1e-9d, - DensityUnit.NanogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-9d, - DensityUnit.PicogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-12d, - DensityUnit.PicogramPerLiter => (baseUnitValue * 1) / 1e-12d, - DensityUnit.PicogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-12d, - DensityUnit.PoundPerCubicCentimeter => baseUnitValue * 2.204622621848775e-6, - DensityUnit.PoundPerCubicFoot => baseUnitValue * 0.062427961, - DensityUnit.PoundPerCubicInch => baseUnitValue * 3.6127298147753e-5, - DensityUnit.PoundPerCubicMeter => baseUnitValue * 2.204622621848775, - DensityUnit.PoundPerCubicMillimeter => baseUnitValue * 2.204622621848775e-9, - DensityUnit.PoundPerImperialGallon => baseUnitValue / 9.9776398e1, - DensityUnit.PoundPerUSGallon => baseUnitValue / 1.19826427e2, - DensityUnit.SlugPerCubicCentimeter => baseUnitValue / 14593903, - DensityUnit.SlugPerCubicFoot => baseUnitValue * 0.00194032033, - DensityUnit.SlugPerCubicInch => baseUnitValue / 890574.60201535, - DensityUnit.SlugPerCubicMeter => baseUnitValue / 14.5939, - DensityUnit.SlugPerCubicMillimeter => baseUnitValue / 14593903000, - DensityUnit.TonnePerCubicCentimeter => baseUnitValue * 1e-9, - DensityUnit.TonnePerCubicFoot => baseUnitValue / 3.53146667214886e4, - DensityUnit.TonnePerCubicInch => baseUnitValue / 6.10237440947323e7, - DensityUnit.TonnePerCubicMeter => baseUnitValue * 0.001, - DensityUnit.TonnePerCubicMillimeter => baseUnitValue * 1e-12, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Density ToUnit(DensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Density(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + DensityUnit.CentigramPerDeciliter => (_value / 1e-1) * 1e-2d, + DensityUnit.CentigramPerLiter => (_value / 1) * 1e-2d, + DensityUnit.CentigramPerMilliliter => (_value / 1e-3) * 1e-2d, + DensityUnit.DecigramPerDeciliter => (_value / 1e-1) * 1e-1d, + DensityUnit.DecigramPerLiter => (_value / 1) * 1e-1d, + DensityUnit.DecigramPerMilliliter => (_value / 1e-3) * 1e-1d, + DensityUnit.GramPerCubicCentimeter => _value / 1e-3, + DensityUnit.GramPerCubicFoot => _value * 0.0353146667214886, + DensityUnit.GramPerCubicInch => _value * 61.0237440947323, + DensityUnit.GramPerCubicMeter => _value / 1e3, + DensityUnit.GramPerCubicMillimeter => _value / 1e-6, + DensityUnit.GramPerDeciliter => _value / 1e-1, + DensityUnit.GramPerLiter => _value / 1, + DensityUnit.GramPerMilliliter => _value / 1e-3, + DensityUnit.KilogramPerCubicCentimeter => (_value / 1e-3) * 1e3d, + DensityUnit.KilogramPerCubicMeter => (_value / 1e3) * 1e3d, + DensityUnit.KilogramPerCubicMillimeter => (_value / 1e-6) * 1e3d, + DensityUnit.KilogramPerLiter => _value * 1e3, + DensityUnit.KilopoundPerCubicFoot => (_value / 0.062427961) * 1e3d, + DensityUnit.KilopoundPerCubicInch => (_value / 3.6127298147753e-5) * 1e3d, + DensityUnit.MicrogramPerCubicMeter => (_value / 1e3) * 1e-6d, + DensityUnit.MicrogramPerDeciliter => (_value / 1e-1) * 1e-6d, + DensityUnit.MicrogramPerLiter => (_value / 1) * 1e-6d, + DensityUnit.MicrogramPerMilliliter => (_value / 1e-3) * 1e-6d, + DensityUnit.MilligramPerCubicMeter => (_value / 1e3) * 1e-3d, + DensityUnit.MilligramPerDeciliter => (_value / 1e-1) * 1e-3d, + DensityUnit.MilligramPerLiter => (_value / 1) * 1e-3d, + DensityUnit.MilligramPerMilliliter => (_value / 1e-3) * 1e-3d, + DensityUnit.NanogramPerDeciliter => (_value / 1e-1) * 1e-9d, + DensityUnit.NanogramPerLiter => (_value / 1) * 1e-9d, + DensityUnit.NanogramPerMilliliter => (_value / 1e-3) * 1e-9d, + DensityUnit.PicogramPerDeciliter => (_value / 1e-1) * 1e-12d, + DensityUnit.PicogramPerLiter => (_value / 1) * 1e-12d, + DensityUnit.PicogramPerMilliliter => (_value / 1e-3) * 1e-12d, + DensityUnit.PoundPerCubicCentimeter => _value / 2.204622621848775e-6, + DensityUnit.PoundPerCubicFoot => _value / 0.062427961, + DensityUnit.PoundPerCubicInch => _value / 3.6127298147753e-5, + DensityUnit.PoundPerCubicMeter => _value / 2.204622621848775, + DensityUnit.PoundPerCubicMillimeter => _value / 2.204622621848775e-9, + DensityUnit.PoundPerImperialGallon => _value * 9.9776398e1, + DensityUnit.PoundPerUSGallon => _value * 1.19826427e2, + DensityUnit.SlugPerCubicCentimeter => _value * 14593903, + DensityUnit.SlugPerCubicFoot => _value * 515.378818, + DensityUnit.SlugPerCubicInch => _value * 890574.60201535, + DensityUnit.SlugPerCubicMeter => _value * 14.5939, + DensityUnit.SlugPerCubicMillimeter => _value * 14593903000, + DensityUnit.TonnePerCubicCentimeter => _value / 1e-9, + DensityUnit.TonnePerCubicFoot => _value * 3.53146667214886e4, + DensityUnit.TonnePerCubicInch => _value * 6.10237440947323e7, + DensityUnit.TonnePerCubicMeter => _value / 0.001, + DensityUnit.TonnePerCubicMillimeter => _value / 1e-12, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(DensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + DensityUnit.CentigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-2d, + DensityUnit.CentigramPerLiter => (baseUnitValue * 1) / 1e-2d, + DensityUnit.CentigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-2d, + DensityUnit.DecigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-1d, + DensityUnit.DecigramPerLiter => (baseUnitValue * 1) / 1e-1d, + DensityUnit.DecigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-1d, + DensityUnit.GramPerCubicCentimeter => baseUnitValue * 1e-3, + DensityUnit.GramPerCubicFoot => baseUnitValue / 0.0353146667214886, + DensityUnit.GramPerCubicInch => baseUnitValue / 61.0237440947323, + DensityUnit.GramPerCubicMeter => baseUnitValue * 1e3, + DensityUnit.GramPerCubicMillimeter => baseUnitValue * 1e-6, + DensityUnit.GramPerDeciliter => baseUnitValue * 1e-1, + DensityUnit.GramPerLiter => baseUnitValue * 1, + DensityUnit.GramPerMilliliter => baseUnitValue * 1e-3, + DensityUnit.KilogramPerCubicCentimeter => (baseUnitValue * 1e-3) / 1e3d, + DensityUnit.KilogramPerCubicMeter => (baseUnitValue * 1e3) / 1e3d, + DensityUnit.KilogramPerCubicMillimeter => (baseUnitValue * 1e-6) / 1e3d, + DensityUnit.KilogramPerLiter => baseUnitValue / 1e3, + DensityUnit.KilopoundPerCubicFoot => (baseUnitValue * 0.062427961) / 1e3d, + DensityUnit.KilopoundPerCubicInch => (baseUnitValue * 3.6127298147753e-5) / 1e3d, + DensityUnit.MicrogramPerCubicMeter => (baseUnitValue * 1e3) / 1e-6d, + DensityUnit.MicrogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-6d, + DensityUnit.MicrogramPerLiter => (baseUnitValue * 1) / 1e-6d, + DensityUnit.MicrogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-6d, + DensityUnit.MilligramPerCubicMeter => (baseUnitValue * 1e3) / 1e-3d, + DensityUnit.MilligramPerDeciliter => (baseUnitValue * 1e-1) / 1e-3d, + DensityUnit.MilligramPerLiter => (baseUnitValue * 1) / 1e-3d, + DensityUnit.MilligramPerMilliliter => (baseUnitValue * 1e-3) / 1e-3d, + DensityUnit.NanogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-9d, + DensityUnit.NanogramPerLiter => (baseUnitValue * 1) / 1e-9d, + DensityUnit.NanogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-9d, + DensityUnit.PicogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-12d, + DensityUnit.PicogramPerLiter => (baseUnitValue * 1) / 1e-12d, + DensityUnit.PicogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-12d, + DensityUnit.PoundPerCubicCentimeter => baseUnitValue * 2.204622621848775e-6, + DensityUnit.PoundPerCubicFoot => baseUnitValue * 0.062427961, + DensityUnit.PoundPerCubicInch => baseUnitValue * 3.6127298147753e-5, + DensityUnit.PoundPerCubicMeter => baseUnitValue * 2.204622621848775, + DensityUnit.PoundPerCubicMillimeter => baseUnitValue * 2.204622621848775e-9, + DensityUnit.PoundPerImperialGallon => baseUnitValue / 9.9776398e1, + DensityUnit.PoundPerUSGallon => baseUnitValue / 1.19826427e2, + DensityUnit.SlugPerCubicCentimeter => baseUnitValue / 14593903, + DensityUnit.SlugPerCubicFoot => baseUnitValue * 0.00194032033, + DensityUnit.SlugPerCubicInch => baseUnitValue / 890574.60201535, + DensityUnit.SlugPerCubicMeter => baseUnitValue / 14.5939, + DensityUnit.SlugPerCubicMillimeter => baseUnitValue / 14593903000, + DensityUnit.TonnePerCubicCentimeter => baseUnitValue * 1e-9, + DensityUnit.TonnePerCubicFoot => baseUnitValue / 3.53146667214886e4, + DensityUnit.TonnePerCubicInch => baseUnitValue / 6.10237440947323e7, + DensityUnit.TonnePerCubicMeter => baseUnitValue * 0.001, + DensityUnit.TonnePerCubicMillimeter => baseUnitValue * 1e-12, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Duration.g.cs index 1c4219480e..c9d8672474 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Duration.g.cs @@ -217,73 +217,73 @@ public static Duration From(double value, DurationUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DurationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Duration ToUnit(DurationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Duration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - DurationUnit.Day => _value * 24 * 3600, - DurationUnit.Hour => _value * 3600, - DurationUnit.JulianYear => _value * 365.25 * 24 * 3600, - DurationUnit.Microsecond => (_value) * 1e-6d, - DurationUnit.Millisecond => (_value) * 1e-3d, - DurationUnit.Minute => _value * 60, - DurationUnit.Month30 => _value * 30 * 24 * 3600, - DurationUnit.Nanosecond => (_value) * 1e-9d, - DurationUnit.Second => _value, - DurationUnit.Week => _value * 7 * 24 * 3600, - DurationUnit.Year365 => _value * 365 * 24 * 3600, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(DurationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - DurationUnit.Day => baseUnitValue / (24 * 3600), - DurationUnit.Hour => baseUnitValue / 3600, - DurationUnit.JulianYear => baseUnitValue / (365.25 * 24 * 3600), - DurationUnit.Microsecond => (baseUnitValue) / 1e-6d, - DurationUnit.Millisecond => (baseUnitValue) / 1e-3d, - DurationUnit.Minute => baseUnitValue / 60, - DurationUnit.Month30 => baseUnitValue / (30 * 24 * 3600), - DurationUnit.Nanosecond => (baseUnitValue) / 1e-9d, - DurationUnit.Second => baseUnitValue, - DurationUnit.Week => baseUnitValue / (7 * 24 * 3600), - DurationUnit.Year365 => baseUnitValue / (365 * 24 * 3600), - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DurationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Duration ToUnit(DurationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Duration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + DurationUnit.Day => _value * 24 * 3600, + DurationUnit.Hour => _value * 3600, + DurationUnit.JulianYear => _value * 365.25 * 24 * 3600, + DurationUnit.Microsecond => (_value) * 1e-6d, + DurationUnit.Millisecond => (_value) * 1e-3d, + DurationUnit.Minute => _value * 60, + DurationUnit.Month30 => _value * 30 * 24 * 3600, + DurationUnit.Nanosecond => (_value) * 1e-9d, + DurationUnit.Second => _value, + DurationUnit.Week => _value * 7 * 24 * 3600, + DurationUnit.Year365 => _value * 365 * 24 * 3600, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(DurationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + DurationUnit.Day => baseUnitValue / (24 * 3600), + DurationUnit.Hour => baseUnitValue / 3600, + DurationUnit.JulianYear => baseUnitValue / (365.25 * 24 * 3600), + DurationUnit.Microsecond => (baseUnitValue) / 1e-6d, + DurationUnit.Millisecond => (baseUnitValue) / 1e-3d, + DurationUnit.Minute => baseUnitValue / 60, + DurationUnit.Month30 => baseUnitValue / (30 * 24 * 3600), + DurationUnit.Nanosecond => (baseUnitValue) / 1e-9d, + DurationUnit.Second => baseUnitValue, + DurationUnit.Week => baseUnitValue / (7 * 24 * 3600), + DurationUnit.Year365 => baseUnitValue / (365 * 24 * 3600), + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/DynamicViscosity.g.cs index 72ae060f58..27ca67f70a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -209,71 +209,71 @@ public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DynamicViscosityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public DynamicViscosity ToUnit(DynamicViscosityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new DynamicViscosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - DynamicViscosityUnit.Centipoise => (_value / 10) * 1e-2d, - DynamicViscosityUnit.MicropascalSecond => (_value) * 1e-6d, - DynamicViscosityUnit.MillipascalSecond => (_value) * 1e-3d, - DynamicViscosityUnit.NewtonSecondPerMeterSquared => _value, - DynamicViscosityUnit.PascalSecond => _value, - DynamicViscosityUnit.Poise => _value / 10, - DynamicViscosityUnit.PoundForceSecondPerSquareFoot => _value * 4.7880258980335843e1, - DynamicViscosityUnit.PoundForceSecondPerSquareInch => _value * 6.8947572931683613e3, - DynamicViscosityUnit.PoundPerFootSecond => _value * 1.4881639, - DynamicViscosityUnit.Reyn => _value * 6.8947572931683613e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(DynamicViscosityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - DynamicViscosityUnit.Centipoise => (baseUnitValue * 10) / 1e-2d, - DynamicViscosityUnit.MicropascalSecond => (baseUnitValue) / 1e-6d, - DynamicViscosityUnit.MillipascalSecond => (baseUnitValue) / 1e-3d, - DynamicViscosityUnit.NewtonSecondPerMeterSquared => baseUnitValue, - DynamicViscosityUnit.PascalSecond => baseUnitValue, - DynamicViscosityUnit.Poise => baseUnitValue * 10, - DynamicViscosityUnit.PoundForceSecondPerSquareFoot => baseUnitValue / 4.7880258980335843e1, - DynamicViscosityUnit.PoundForceSecondPerSquareInch => baseUnitValue / 6.8947572931683613e3, - DynamicViscosityUnit.PoundPerFootSecond => baseUnitValue / 1.4881639, - DynamicViscosityUnit.Reyn => baseUnitValue / 6.8947572931683613e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(DynamicViscosityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public DynamicViscosity ToUnit(DynamicViscosityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new DynamicViscosity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + DynamicViscosityUnit.Centipoise => (_value / 10) * 1e-2d, + DynamicViscosityUnit.MicropascalSecond => (_value) * 1e-6d, + DynamicViscosityUnit.MillipascalSecond => (_value) * 1e-3d, + DynamicViscosityUnit.NewtonSecondPerMeterSquared => _value, + DynamicViscosityUnit.PascalSecond => _value, + DynamicViscosityUnit.Poise => _value / 10, + DynamicViscosityUnit.PoundForceSecondPerSquareFoot => _value * 4.7880258980335843e1, + DynamicViscosityUnit.PoundForceSecondPerSquareInch => _value * 6.8947572931683613e3, + DynamicViscosityUnit.PoundPerFootSecond => _value * 1.4881639, + DynamicViscosityUnit.Reyn => _value * 6.8947572931683613e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(DynamicViscosityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + DynamicViscosityUnit.Centipoise => (baseUnitValue * 10) / 1e-2d, + DynamicViscosityUnit.MicropascalSecond => (baseUnitValue) / 1e-6d, + DynamicViscosityUnit.MillipascalSecond => (baseUnitValue) / 1e-3d, + DynamicViscosityUnit.NewtonSecondPerMeterSquared => baseUnitValue, + DynamicViscosityUnit.PascalSecond => baseUnitValue, + DynamicViscosityUnit.Poise => baseUnitValue * 10, + DynamicViscosityUnit.PoundForceSecondPerSquareFoot => baseUnitValue / 4.7880258980335843e1, + DynamicViscosityUnit.PoundForceSecondPerSquareInch => baseUnitValue / 6.8947572931683613e3, + DynamicViscosityUnit.PoundPerFootSecond => baseUnitValue / 1.4881639, + DynamicViscosityUnit.Reyn => baseUnitValue / 6.8947572931683613e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricAdmittance.g.cs index 7b6f52167c..c7baaf955f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -140,59 +140,59 @@ public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricAdmittanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricAdmittance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricAdmittanceUnit.Microsiemens => (_value) * 1e-6d, - ElectricAdmittanceUnit.Millisiemens => (_value) * 1e-3d, - ElectricAdmittanceUnit.Nanosiemens => (_value) * 1e-9d, - ElectricAdmittanceUnit.Siemens => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricAdmittanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricAdmittanceUnit.Microsiemens => (baseUnitValue) / 1e-6d, - ElectricAdmittanceUnit.Millisiemens => (baseUnitValue) / 1e-3d, - ElectricAdmittanceUnit.Nanosiemens => (baseUnitValue) / 1e-9d, - ElectricAdmittanceUnit.Siemens => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricAdmittanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricAdmittance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricAdmittanceUnit.Microsiemens => (_value) * 1e-6d, + ElectricAdmittanceUnit.Millisiemens => (_value) * 1e-3d, + ElectricAdmittanceUnit.Nanosiemens => (_value) * 1e-9d, + ElectricAdmittanceUnit.Siemens => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricAdmittanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricAdmittanceUnit.Microsiemens => (baseUnitValue) / 1e-6d, + ElectricAdmittanceUnit.Millisiemens => (baseUnitValue) / 1e-3d, + ElectricAdmittanceUnit.Nanosiemens => (baseUnitValue) / 1e-9d, + ElectricAdmittanceUnit.Siemens => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCharge.g.cs index c582c49d4c..7039032361 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -154,61 +154,61 @@ public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricCharge ToUnit(ElectricChargeUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricCharge(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricChargeUnit.AmpereHour => _value / 2.77777777777e-4, - ElectricChargeUnit.Coulomb => _value, - ElectricChargeUnit.KiloampereHour => (_value / 2.77777777777e-4) * 1e3d, - ElectricChargeUnit.MegaampereHour => (_value / 2.77777777777e-4) * 1e6d, - ElectricChargeUnit.MilliampereHour => (_value / 2.77777777777e-4) * 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricChargeUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricChargeUnit.AmpereHour => baseUnitValue * 2.77777777777e-4, - ElectricChargeUnit.Coulomb => baseUnitValue, - ElectricChargeUnit.KiloampereHour => (baseUnitValue * 2.77777777777e-4) / 1e3d, - ElectricChargeUnit.MegaampereHour => (baseUnitValue * 2.77777777777e-4) / 1e6d, - ElectricChargeUnit.MilliampereHour => (baseUnitValue * 2.77777777777e-4) / 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricChargeUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricCharge ToUnit(ElectricChargeUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricCharge(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricChargeUnit.AmpereHour => _value / 2.77777777777e-4, + ElectricChargeUnit.Coulomb => _value, + ElectricChargeUnit.KiloampereHour => (_value / 2.77777777777e-4) * 1e3d, + ElectricChargeUnit.MegaampereHour => (_value / 2.77777777777e-4) * 1e6d, + ElectricChargeUnit.MilliampereHour => (_value / 2.77777777777e-4) * 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricChargeUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricChargeUnit.AmpereHour => baseUnitValue * 2.77777777777e-4, + ElectricChargeUnit.Coulomb => baseUnitValue, + ElectricChargeUnit.KiloampereHour => (baseUnitValue * 2.77777777777e-4) / 1e3d, + ElectricChargeUnit.MegaampereHour => (baseUnitValue * 2.77777777777e-4) / 1e6d, + ElectricChargeUnit.MilliampereHour => (baseUnitValue * 2.77777777777e-4) / 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index 52b67fd075..8a0d0b1eb9 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -110,53 +110,53 @@ public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricChargeDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricChargeDensityUnit.CoulombPerCubicMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricChargeDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricChargeDensityUnit.CoulombPerCubicMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricChargeDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricChargeDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricChargeDensityUnit.CoulombPerCubicMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricChargeDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricChargeDensityUnit.CoulombPerCubicMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductance.g.cs index fd1f3b2470..0e7ff5fab7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -132,57 +132,57 @@ public static ElectricConductance From(double value, ElectricConductanceUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricConductance ToUnit(ElectricConductanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricConductance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricConductanceUnit.Microsiemens => (_value) * 1e-6d, - ElectricConductanceUnit.Millisiemens => (_value) * 1e-3d, - ElectricConductanceUnit.Siemens => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricConductanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricConductanceUnit.Microsiemens => (baseUnitValue) / 1e-6d, - ElectricConductanceUnit.Millisiemens => (baseUnitValue) / 1e-3d, - ElectricConductanceUnit.Siemens => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricConductanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricConductance ToUnit(ElectricConductanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricConductance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricConductanceUnit.Microsiemens => (_value) * 1e-6d, + ElectricConductanceUnit.Millisiemens => (_value) * 1e-3d, + ElectricConductanceUnit.Siemens => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricConductanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricConductanceUnit.Microsiemens => (baseUnitValue) / 1e-6d, + ElectricConductanceUnit.Millisiemens => (baseUnitValue) / 1e-3d, + ElectricConductanceUnit.Siemens => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductivity.g.cs index d9ce24b11a..2a6652b9ff 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -165,63 +165,63 @@ public static ElectricConductivity From(double value, ElectricConductivityUnit f #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductivityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricConductivity ToUnit(ElectricConductivityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricConductivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricConductivityUnit.MicrosiemensPerCentimeter => (_value * 1e2) * 1e-6d, - ElectricConductivityUnit.MillisiemensPerCentimeter => (_value * 1e2) * 1e-3d, - ElectricConductivityUnit.SiemensPerCentimeter => _value * 1e2, - ElectricConductivityUnit.SiemensPerFoot => _value * 3.2808398950131234, - ElectricConductivityUnit.SiemensPerInch => _value * 3.937007874015748e1, - ElectricConductivityUnit.SiemensPerMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricConductivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricConductivityUnit.MicrosiemensPerCentimeter => (baseUnitValue / 1e2) / 1e-6d, - ElectricConductivityUnit.MillisiemensPerCentimeter => (baseUnitValue / 1e2) / 1e-3d, - ElectricConductivityUnit.SiemensPerCentimeter => baseUnitValue / 1e2, - ElectricConductivityUnit.SiemensPerFoot => baseUnitValue / 3.2808398950131234, - ElectricConductivityUnit.SiemensPerInch => baseUnitValue / 3.937007874015748e1, - ElectricConductivityUnit.SiemensPerMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricConductivityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricConductivity ToUnit(ElectricConductivityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricConductivity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricConductivityUnit.MicrosiemensPerCentimeter => (_value * 1e2) * 1e-6d, + ElectricConductivityUnit.MillisiemensPerCentimeter => (_value * 1e2) * 1e-3d, + ElectricConductivityUnit.SiemensPerCentimeter => _value * 1e2, + ElectricConductivityUnit.SiemensPerFoot => _value * 3.2808398950131234, + ElectricConductivityUnit.SiemensPerInch => _value * 3.937007874015748e1, + ElectricConductivityUnit.SiemensPerMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricConductivityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricConductivityUnit.MicrosiemensPerCentimeter => (baseUnitValue / 1e2) / 1e-6d, + ElectricConductivityUnit.MillisiemensPerCentimeter => (baseUnitValue / 1e2) / 1e-3d, + ElectricConductivityUnit.SiemensPerCentimeter => baseUnitValue / 1e2, + ElectricConductivityUnit.SiemensPerFoot => baseUnitValue / 3.2808398950131234, + ElectricConductivityUnit.SiemensPerInch => baseUnitValue / 3.937007874015748e1, + ElectricConductivityUnit.SiemensPerMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrent.g.cs index ef21be7da3..a984520ff2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -184,67 +184,67 @@ public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricCurrent ToUnit(ElectricCurrentUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricCurrent(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricCurrentUnit.Ampere => _value, - ElectricCurrentUnit.Centiampere => (_value) * 1e-2d, - ElectricCurrentUnit.Kiloampere => (_value) * 1e3d, - ElectricCurrentUnit.Megaampere => (_value) * 1e6d, - ElectricCurrentUnit.Microampere => (_value) * 1e-6d, - ElectricCurrentUnit.Milliampere => (_value) * 1e-3d, - ElectricCurrentUnit.Nanoampere => (_value) * 1e-9d, - ElectricCurrentUnit.Picoampere => (_value) * 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricCurrentUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricCurrentUnit.Ampere => baseUnitValue, - ElectricCurrentUnit.Centiampere => (baseUnitValue) / 1e-2d, - ElectricCurrentUnit.Kiloampere => (baseUnitValue) / 1e3d, - ElectricCurrentUnit.Megaampere => (baseUnitValue) / 1e6d, - ElectricCurrentUnit.Microampere => (baseUnitValue) / 1e-6d, - ElectricCurrentUnit.Milliampere => (baseUnitValue) / 1e-3d, - ElectricCurrentUnit.Nanoampere => (baseUnitValue) / 1e-9d, - ElectricCurrentUnit.Picoampere => (baseUnitValue) / 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricCurrent ToUnit(ElectricCurrentUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricCurrent(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricCurrentUnit.Ampere => _value, + ElectricCurrentUnit.Centiampere => (_value) * 1e-2d, + ElectricCurrentUnit.Kiloampere => (_value) * 1e3d, + ElectricCurrentUnit.Megaampere => (_value) * 1e6d, + ElectricCurrentUnit.Microampere => (_value) * 1e-6d, + ElectricCurrentUnit.Milliampere => (_value) * 1e-3d, + ElectricCurrentUnit.Nanoampere => (_value) * 1e-9d, + ElectricCurrentUnit.Picoampere => (_value) * 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricCurrentUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricCurrentUnit.Ampere => baseUnitValue, + ElectricCurrentUnit.Centiampere => (baseUnitValue) / 1e-2d, + ElectricCurrentUnit.Kiloampere => (baseUnitValue) / 1e3d, + ElectricCurrentUnit.Megaampere => (baseUnitValue) / 1e6d, + ElectricCurrentUnit.Microampere => (baseUnitValue) / 1e-6d, + ElectricCurrentUnit.Milliampere => (baseUnitValue) / 1e-3d, + ElectricCurrentUnit.Nanoampere => (baseUnitValue) / 1e-9d, + ElectricCurrentUnit.Picoampere => (baseUnitValue) / 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index c41e5e6363..12a616b2fa 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -132,57 +132,57 @@ public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUn #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricCurrentDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricCurrentDensityUnit.AmperePerSquareFoot => _value * 1.0763910416709722e1, - ElectricCurrentDensityUnit.AmperePerSquareInch => _value * 1.5500031000062000e3, - ElectricCurrentDensityUnit.AmperePerSquareMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricCurrentDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricCurrentDensityUnit.AmperePerSquareFoot => baseUnitValue / 1.0763910416709722e1, - ElectricCurrentDensityUnit.AmperePerSquareInch => baseUnitValue / 1.5500031000062000e3, - ElectricCurrentDensityUnit.AmperePerSquareMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricCurrentDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricCurrentDensityUnit.AmperePerSquareFoot => _value * 1.0763910416709722e1, + ElectricCurrentDensityUnit.AmperePerSquareInch => _value * 1.5500031000062000e3, + ElectricCurrentDensityUnit.AmperePerSquareMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricCurrentDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricCurrentDensityUnit.AmperePerSquareFoot => baseUnitValue / 1.0763910416709722e1, + ElectricCurrentDensityUnit.AmperePerSquareInch => baseUnitValue / 1.5500031000062000e3, + ElectricCurrentDensityUnit.AmperePerSquareMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index 461b8d3f00..cbd99cb602 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -140,59 +140,59 @@ public static ElectricCurrentGradient From(double value, ElectricCurrentGradient #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentGradientUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricCurrentGradient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricCurrentGradientUnit.AmperePerMicrosecond => _value * 1E6, - ElectricCurrentGradientUnit.AmperePerMillisecond => _value * 1E3, - ElectricCurrentGradientUnit.AmperePerNanosecond => _value * 1E9, - ElectricCurrentGradientUnit.AmperePerSecond => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricCurrentGradientUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricCurrentGradientUnit.AmperePerMicrosecond => baseUnitValue / 1E6, - ElectricCurrentGradientUnit.AmperePerMillisecond => baseUnitValue / 1E3, - ElectricCurrentGradientUnit.AmperePerNanosecond => baseUnitValue / 1E9, - ElectricCurrentGradientUnit.AmperePerSecond => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricCurrentGradientUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricCurrentGradient(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricCurrentGradientUnit.AmperePerMicrosecond => _value * 1E6, + ElectricCurrentGradientUnit.AmperePerMillisecond => _value * 1E3, + ElectricCurrentGradientUnit.AmperePerNanosecond => _value * 1E9, + ElectricCurrentGradientUnit.AmperePerSecond => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricCurrentGradientUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricCurrentGradientUnit.AmperePerMicrosecond => baseUnitValue / 1E6, + ElectricCurrentGradientUnit.AmperePerMillisecond => baseUnitValue / 1E3, + ElectricCurrentGradientUnit.AmperePerNanosecond => baseUnitValue / 1E9, + ElectricCurrentGradientUnit.AmperePerSecond => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricField.g.cs index 0299670c0e..9e57f46eec 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricField.g.cs @@ -110,53 +110,53 @@ public static ElectricField From(double value, ElectricFieldUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricFieldUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricField ToUnit(ElectricFieldUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricField(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricFieldUnit.VoltPerMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricFieldUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricFieldUnit.VoltPerMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricFieldUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricField ToUnit(ElectricFieldUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricField(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricFieldUnit.VoltPerMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricFieldUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricFieldUnit.VoltPerMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricInductance.g.cs index d5cf764b8b..1f3142372b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -143,59 +143,59 @@ public static ElectricInductance From(double value, ElectricInductanceUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricInductanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricInductance ToUnit(ElectricInductanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricInductance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricInductanceUnit.Henry => _value, - ElectricInductanceUnit.Microhenry => (_value) * 1e-6d, - ElectricInductanceUnit.Millihenry => (_value) * 1e-3d, - ElectricInductanceUnit.Nanohenry => (_value) * 1e-9d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricInductanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricInductanceUnit.Henry => baseUnitValue, - ElectricInductanceUnit.Microhenry => (baseUnitValue) / 1e-6d, - ElectricInductanceUnit.Millihenry => (baseUnitValue) / 1e-3d, - ElectricInductanceUnit.Nanohenry => (baseUnitValue) / 1e-9d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricInductanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricInductance ToUnit(ElectricInductanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricInductance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricInductanceUnit.Henry => _value, + ElectricInductanceUnit.Microhenry => (_value) * 1e-6d, + ElectricInductanceUnit.Millihenry => (_value) * 1e-3d, + ElectricInductanceUnit.Nanohenry => (_value) * 1e-9d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricInductanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricInductanceUnit.Henry => baseUnitValue, + ElectricInductanceUnit.Microhenry => (baseUnitValue) / 1e-6d, + ElectricInductanceUnit.Millihenry => (baseUnitValue) / 1e-3d, + ElectricInductanceUnit.Nanohenry => (baseUnitValue) / 1e-9d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotential.g.cs index 1bb2ded2fa..59cd4ad83b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -151,61 +151,61 @@ public static ElectricPotential From(double value, ElectricPotentialUnit fromUni #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricPotential ToUnit(ElectricPotentialUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricPotential(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricPotentialUnit.Kilovolt => (_value) * 1e3d, - ElectricPotentialUnit.Megavolt => (_value) * 1e6d, - ElectricPotentialUnit.Microvolt => (_value) * 1e-6d, - ElectricPotentialUnit.Millivolt => (_value) * 1e-3d, - ElectricPotentialUnit.Volt => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricPotentialUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricPotentialUnit.Kilovolt => (baseUnitValue) / 1e3d, - ElectricPotentialUnit.Megavolt => (baseUnitValue) / 1e6d, - ElectricPotentialUnit.Microvolt => (baseUnitValue) / 1e-6d, - ElectricPotentialUnit.Millivolt => (baseUnitValue) / 1e-3d, - ElectricPotentialUnit.Volt => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricPotential ToUnit(ElectricPotentialUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricPotential(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricPotentialUnit.Kilovolt => (_value) * 1e3d, + ElectricPotentialUnit.Megavolt => (_value) * 1e6d, + ElectricPotentialUnit.Microvolt => (_value) * 1e-6d, + ElectricPotentialUnit.Millivolt => (_value) * 1e-3d, + ElectricPotentialUnit.Volt => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricPotentialUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricPotentialUnit.Kilovolt => (baseUnitValue) / 1e3d, + ElectricPotentialUnit.Megavolt => (baseUnitValue) / 1e6d, + ElectricPotentialUnit.Microvolt => (baseUnitValue) / 1e-6d, + ElectricPotentialUnit.Millivolt => (baseUnitValue) / 1e-3d, + ElectricPotentialUnit.Volt => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialAc.g.cs index e6ac628898..80aef9db9e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialAc.g.cs @@ -151,61 +151,61 @@ public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialAcUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricPotentialAc(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricPotentialAcUnit.KilovoltAc => (_value) * 1e3d, - ElectricPotentialAcUnit.MegavoltAc => (_value) * 1e6d, - ElectricPotentialAcUnit.MicrovoltAc => (_value) * 1e-6d, - ElectricPotentialAcUnit.MillivoltAc => (_value) * 1e-3d, - ElectricPotentialAcUnit.VoltAc => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricPotentialAcUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricPotentialAcUnit.KilovoltAc => (baseUnitValue) / 1e3d, - ElectricPotentialAcUnit.MegavoltAc => (baseUnitValue) / 1e6d, - ElectricPotentialAcUnit.MicrovoltAc => (baseUnitValue) / 1e-6d, - ElectricPotentialAcUnit.MillivoltAc => (baseUnitValue) / 1e-3d, - ElectricPotentialAcUnit.VoltAc => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialAcUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricPotentialAc(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricPotentialAcUnit.KilovoltAc => (_value) * 1e3d, + ElectricPotentialAcUnit.MegavoltAc => (_value) * 1e6d, + ElectricPotentialAcUnit.MicrovoltAc => (_value) * 1e-6d, + ElectricPotentialAcUnit.MillivoltAc => (_value) * 1e-3d, + ElectricPotentialAcUnit.VoltAc => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricPotentialAcUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricPotentialAcUnit.KilovoltAc => (baseUnitValue) / 1e3d, + ElectricPotentialAcUnit.MegavoltAc => (baseUnitValue) / 1e6d, + ElectricPotentialAcUnit.MicrovoltAc => (baseUnitValue) / 1e-6d, + ElectricPotentialAcUnit.MillivoltAc => (baseUnitValue) / 1e-3d, + ElectricPotentialAcUnit.VoltAc => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index b16fd5eb40..1ce4ce0ecc 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -316,91 +316,91 @@ public static ElectricPotentialChangeRate From(double value, ElectricPotentialCh #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialChangeRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricPotentialChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricPotentialChangeRateUnit.KilovoltPerHour => (_value / 3600) * 1e3d, - ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond => (_value * 1E6) * 1e3d, - ElectricPotentialChangeRateUnit.KilovoltPerMinute => (_value / 60) * 1e3d, - ElectricPotentialChangeRateUnit.KilovoltPerSecond => (_value) * 1e3d, - ElectricPotentialChangeRateUnit.MegavoltPerHour => (_value / 3600) * 1e6d, - ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond => (_value * 1E6) * 1e6d, - ElectricPotentialChangeRateUnit.MegavoltPerMinute => (_value / 60) * 1e6d, - ElectricPotentialChangeRateUnit.MegavoltPerSecond => (_value) * 1e6d, - ElectricPotentialChangeRateUnit.MicrovoltPerHour => (_value / 3600) * 1e-6d, - ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond => (_value * 1E6) * 1e-6d, - ElectricPotentialChangeRateUnit.MicrovoltPerMinute => (_value / 60) * 1e-6d, - ElectricPotentialChangeRateUnit.MicrovoltPerSecond => (_value) * 1e-6d, - ElectricPotentialChangeRateUnit.MillivoltPerHour => (_value / 3600) * 1e-3d, - ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond => (_value * 1E6) * 1e-3d, - ElectricPotentialChangeRateUnit.MillivoltPerMinute => (_value / 60) * 1e-3d, - ElectricPotentialChangeRateUnit.MillivoltPerSecond => (_value) * 1e-3d, - ElectricPotentialChangeRateUnit.VoltPerHour => _value / 3600, - ElectricPotentialChangeRateUnit.VoltPerMicrosecond => _value * 1E6, - ElectricPotentialChangeRateUnit.VoltPerMinute => _value / 60, - ElectricPotentialChangeRateUnit.VoltPerSecond => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricPotentialChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricPotentialChangeRateUnit.KilovoltPerHour => (baseUnitValue * 3600) / 1e3d, - ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond => (baseUnitValue / 1E6) / 1e3d, - ElectricPotentialChangeRateUnit.KilovoltPerMinute => (baseUnitValue * 60) / 1e3d, - ElectricPotentialChangeRateUnit.KilovoltPerSecond => (baseUnitValue) / 1e3d, - ElectricPotentialChangeRateUnit.MegavoltPerHour => (baseUnitValue * 3600) / 1e6d, - ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond => (baseUnitValue / 1E6) / 1e6d, - ElectricPotentialChangeRateUnit.MegavoltPerMinute => (baseUnitValue * 60) / 1e6d, - ElectricPotentialChangeRateUnit.MegavoltPerSecond => (baseUnitValue) / 1e6d, - ElectricPotentialChangeRateUnit.MicrovoltPerHour => (baseUnitValue * 3600) / 1e-6d, - ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond => (baseUnitValue / 1E6) / 1e-6d, - ElectricPotentialChangeRateUnit.MicrovoltPerMinute => (baseUnitValue * 60) / 1e-6d, - ElectricPotentialChangeRateUnit.MicrovoltPerSecond => (baseUnitValue) / 1e-6d, - ElectricPotentialChangeRateUnit.MillivoltPerHour => (baseUnitValue * 3600) / 1e-3d, - ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond => (baseUnitValue / 1E6) / 1e-3d, - ElectricPotentialChangeRateUnit.MillivoltPerMinute => (baseUnitValue * 60) / 1e-3d, - ElectricPotentialChangeRateUnit.MillivoltPerSecond => (baseUnitValue) / 1e-3d, - ElectricPotentialChangeRateUnit.VoltPerHour => baseUnitValue * 3600, - ElectricPotentialChangeRateUnit.VoltPerMicrosecond => baseUnitValue / 1E6, - ElectricPotentialChangeRateUnit.VoltPerMinute => baseUnitValue * 60, - ElectricPotentialChangeRateUnit.VoltPerSecond => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialChangeRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricPotentialChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricPotentialChangeRateUnit.KilovoltPerHour => (_value / 3600) * 1e3d, + ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond => (_value * 1E6) * 1e3d, + ElectricPotentialChangeRateUnit.KilovoltPerMinute => (_value / 60) * 1e3d, + ElectricPotentialChangeRateUnit.KilovoltPerSecond => (_value) * 1e3d, + ElectricPotentialChangeRateUnit.MegavoltPerHour => (_value / 3600) * 1e6d, + ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond => (_value * 1E6) * 1e6d, + ElectricPotentialChangeRateUnit.MegavoltPerMinute => (_value / 60) * 1e6d, + ElectricPotentialChangeRateUnit.MegavoltPerSecond => (_value) * 1e6d, + ElectricPotentialChangeRateUnit.MicrovoltPerHour => (_value / 3600) * 1e-6d, + ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond => (_value * 1E6) * 1e-6d, + ElectricPotentialChangeRateUnit.MicrovoltPerMinute => (_value / 60) * 1e-6d, + ElectricPotentialChangeRateUnit.MicrovoltPerSecond => (_value) * 1e-6d, + ElectricPotentialChangeRateUnit.MillivoltPerHour => (_value / 3600) * 1e-3d, + ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond => (_value * 1E6) * 1e-3d, + ElectricPotentialChangeRateUnit.MillivoltPerMinute => (_value / 60) * 1e-3d, + ElectricPotentialChangeRateUnit.MillivoltPerSecond => (_value) * 1e-3d, + ElectricPotentialChangeRateUnit.VoltPerHour => _value / 3600, + ElectricPotentialChangeRateUnit.VoltPerMicrosecond => _value * 1E6, + ElectricPotentialChangeRateUnit.VoltPerMinute => _value / 60, + ElectricPotentialChangeRateUnit.VoltPerSecond => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricPotentialChangeRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricPotentialChangeRateUnit.KilovoltPerHour => (baseUnitValue * 3600) / 1e3d, + ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond => (baseUnitValue / 1E6) / 1e3d, + ElectricPotentialChangeRateUnit.KilovoltPerMinute => (baseUnitValue * 60) / 1e3d, + ElectricPotentialChangeRateUnit.KilovoltPerSecond => (baseUnitValue) / 1e3d, + ElectricPotentialChangeRateUnit.MegavoltPerHour => (baseUnitValue * 3600) / 1e6d, + ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond => (baseUnitValue / 1E6) / 1e6d, + ElectricPotentialChangeRateUnit.MegavoltPerMinute => (baseUnitValue * 60) / 1e6d, + ElectricPotentialChangeRateUnit.MegavoltPerSecond => (baseUnitValue) / 1e6d, + ElectricPotentialChangeRateUnit.MicrovoltPerHour => (baseUnitValue * 3600) / 1e-6d, + ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond => (baseUnitValue / 1E6) / 1e-6d, + ElectricPotentialChangeRateUnit.MicrovoltPerMinute => (baseUnitValue * 60) / 1e-6d, + ElectricPotentialChangeRateUnit.MicrovoltPerSecond => (baseUnitValue) / 1e-6d, + ElectricPotentialChangeRateUnit.MillivoltPerHour => (baseUnitValue * 3600) / 1e-3d, + ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond => (baseUnitValue / 1E6) / 1e-3d, + ElectricPotentialChangeRateUnit.MillivoltPerMinute => (baseUnitValue * 60) / 1e-3d, + ElectricPotentialChangeRateUnit.MillivoltPerSecond => (baseUnitValue) / 1e-3d, + ElectricPotentialChangeRateUnit.VoltPerHour => baseUnitValue * 3600, + ElectricPotentialChangeRateUnit.VoltPerMicrosecond => baseUnitValue / 1E6, + ElectricPotentialChangeRateUnit.VoltPerMinute => baseUnitValue * 60, + ElectricPotentialChangeRateUnit.VoltPerSecond => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialDc.g.cs index fb588c7d2e..ae105b1b3b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricPotentialDc.g.cs @@ -151,61 +151,61 @@ public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialDcUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricPotentialDc(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricPotentialDcUnit.KilovoltDc => (_value) * 1e3d, - ElectricPotentialDcUnit.MegavoltDc => (_value) * 1e6d, - ElectricPotentialDcUnit.MicrovoltDc => (_value) * 1e-6d, - ElectricPotentialDcUnit.MillivoltDc => (_value) * 1e-3d, - ElectricPotentialDcUnit.VoltDc => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricPotentialDcUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricPotentialDcUnit.KilovoltDc => (baseUnitValue) / 1e3d, - ElectricPotentialDcUnit.MegavoltDc => (baseUnitValue) / 1e6d, - ElectricPotentialDcUnit.MicrovoltDc => (baseUnitValue) / 1e-6d, - ElectricPotentialDcUnit.MillivoltDc => (baseUnitValue) / 1e-3d, - ElectricPotentialDcUnit.VoltDc => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricPotentialDcUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricPotentialDc(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricPotentialDcUnit.KilovoltDc => (_value) * 1e3d, + ElectricPotentialDcUnit.MegavoltDc => (_value) * 1e6d, + ElectricPotentialDcUnit.MicrovoltDc => (_value) * 1e-6d, + ElectricPotentialDcUnit.MillivoltDc => (_value) * 1e-3d, + ElectricPotentialDcUnit.VoltDc => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricPotentialDcUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricPotentialDcUnit.KilovoltDc => (baseUnitValue) / 1e3d, + ElectricPotentialDcUnit.MegavoltDc => (baseUnitValue) / 1e6d, + ElectricPotentialDcUnit.MicrovoltDc => (baseUnitValue) / 1e-6d, + ElectricPotentialDcUnit.MillivoltDc => (baseUnitValue) / 1e-3d, + ElectricPotentialDcUnit.VoltDc => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistance.g.cs index 24c574ae7e..1e9cfed28a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -162,63 +162,63 @@ public static ElectricResistance From(double value, ElectricResistanceUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricResistance ToUnit(ElectricResistanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricResistance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricResistanceUnit.Gigaohm => (_value) * 1e9d, - ElectricResistanceUnit.Kiloohm => (_value) * 1e3d, - ElectricResistanceUnit.Megaohm => (_value) * 1e6d, - ElectricResistanceUnit.Microohm => (_value) * 1e-6d, - ElectricResistanceUnit.Milliohm => (_value) * 1e-3d, - ElectricResistanceUnit.Ohm => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricResistanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricResistanceUnit.Gigaohm => (baseUnitValue) / 1e9d, - ElectricResistanceUnit.Kiloohm => (baseUnitValue) / 1e3d, - ElectricResistanceUnit.Megaohm => (baseUnitValue) / 1e6d, - ElectricResistanceUnit.Microohm => (baseUnitValue) / 1e-6d, - ElectricResistanceUnit.Milliohm => (baseUnitValue) / 1e-3d, - ElectricResistanceUnit.Ohm => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricResistanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricResistance ToUnit(ElectricResistanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricResistance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricResistanceUnit.Gigaohm => (_value) * 1e9d, + ElectricResistanceUnit.Kiloohm => (_value) * 1e3d, + ElectricResistanceUnit.Megaohm => (_value) * 1e6d, + ElectricResistanceUnit.Microohm => (_value) * 1e-6d, + ElectricResistanceUnit.Milliohm => (_value) * 1e-3d, + ElectricResistanceUnit.Ohm => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricResistanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricResistanceUnit.Gigaohm => (baseUnitValue) / 1e9d, + ElectricResistanceUnit.Kiloohm => (baseUnitValue) / 1e3d, + ElectricResistanceUnit.Megaohm => (baseUnitValue) / 1e6d, + ElectricResistanceUnit.Microohm => (baseUnitValue) / 1e-6d, + ElectricResistanceUnit.Milliohm => (baseUnitValue) / 1e-3d, + ElectricResistanceUnit.Ohm => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistivity.g.cs index 0e966e4d46..7be6e88ecf 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -253,79 +253,79 @@ public static ElectricResistivity From(double value, ElectricResistivityUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistivityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricResistivity ToUnit(ElectricResistivityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricResistivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricResistivityUnit.KiloohmCentimeter => (_value / 100) * 1e3d, - ElectricResistivityUnit.KiloohmMeter => (_value) * 1e3d, - ElectricResistivityUnit.MegaohmCentimeter => (_value / 100) * 1e6d, - ElectricResistivityUnit.MegaohmMeter => (_value) * 1e6d, - ElectricResistivityUnit.MicroohmCentimeter => (_value / 100) * 1e-6d, - ElectricResistivityUnit.MicroohmMeter => (_value) * 1e-6d, - ElectricResistivityUnit.MilliohmCentimeter => (_value / 100) * 1e-3d, - ElectricResistivityUnit.MilliohmMeter => (_value) * 1e-3d, - ElectricResistivityUnit.NanoohmCentimeter => (_value / 100) * 1e-9d, - ElectricResistivityUnit.NanoohmMeter => (_value) * 1e-9d, - ElectricResistivityUnit.OhmCentimeter => _value / 100, - ElectricResistivityUnit.OhmMeter => _value, - ElectricResistivityUnit.PicoohmCentimeter => (_value / 100) * 1e-12d, - ElectricResistivityUnit.PicoohmMeter => (_value) * 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricResistivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricResistivityUnit.KiloohmCentimeter => (baseUnitValue * 100) / 1e3d, - ElectricResistivityUnit.KiloohmMeter => (baseUnitValue) / 1e3d, - ElectricResistivityUnit.MegaohmCentimeter => (baseUnitValue * 100) / 1e6d, - ElectricResistivityUnit.MegaohmMeter => (baseUnitValue) / 1e6d, - ElectricResistivityUnit.MicroohmCentimeter => (baseUnitValue * 100) / 1e-6d, - ElectricResistivityUnit.MicroohmMeter => (baseUnitValue) / 1e-6d, - ElectricResistivityUnit.MilliohmCentimeter => (baseUnitValue * 100) / 1e-3d, - ElectricResistivityUnit.MilliohmMeter => (baseUnitValue) / 1e-3d, - ElectricResistivityUnit.NanoohmCentimeter => (baseUnitValue * 100) / 1e-9d, - ElectricResistivityUnit.NanoohmMeter => (baseUnitValue) / 1e-9d, - ElectricResistivityUnit.OhmCentimeter => baseUnitValue * 100, - ElectricResistivityUnit.OhmMeter => baseUnitValue, - ElectricResistivityUnit.PicoohmCentimeter => (baseUnitValue * 100) / 1e-12d, - ElectricResistivityUnit.PicoohmMeter => (baseUnitValue) / 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricResistivityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricResistivity ToUnit(ElectricResistivityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricResistivity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricResistivityUnit.KiloohmCentimeter => (_value / 100) * 1e3d, + ElectricResistivityUnit.KiloohmMeter => (_value) * 1e3d, + ElectricResistivityUnit.MegaohmCentimeter => (_value / 100) * 1e6d, + ElectricResistivityUnit.MegaohmMeter => (_value) * 1e6d, + ElectricResistivityUnit.MicroohmCentimeter => (_value / 100) * 1e-6d, + ElectricResistivityUnit.MicroohmMeter => (_value) * 1e-6d, + ElectricResistivityUnit.MilliohmCentimeter => (_value / 100) * 1e-3d, + ElectricResistivityUnit.MilliohmMeter => (_value) * 1e-3d, + ElectricResistivityUnit.NanoohmCentimeter => (_value / 100) * 1e-9d, + ElectricResistivityUnit.NanoohmMeter => (_value) * 1e-9d, + ElectricResistivityUnit.OhmCentimeter => _value / 100, + ElectricResistivityUnit.OhmMeter => _value, + ElectricResistivityUnit.PicoohmCentimeter => (_value / 100) * 1e-12d, + ElectricResistivityUnit.PicoohmMeter => (_value) * 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricResistivityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricResistivityUnit.KiloohmCentimeter => (baseUnitValue * 100) / 1e3d, + ElectricResistivityUnit.KiloohmMeter => (baseUnitValue) / 1e3d, + ElectricResistivityUnit.MegaohmCentimeter => (baseUnitValue * 100) / 1e6d, + ElectricResistivityUnit.MegaohmMeter => (baseUnitValue) / 1e6d, + ElectricResistivityUnit.MicroohmCentimeter => (baseUnitValue * 100) / 1e-6d, + ElectricResistivityUnit.MicroohmMeter => (baseUnitValue) / 1e-6d, + ElectricResistivityUnit.MilliohmCentimeter => (baseUnitValue * 100) / 1e-3d, + ElectricResistivityUnit.MilliohmMeter => (baseUnitValue) / 1e-3d, + ElectricResistivityUnit.NanoohmCentimeter => (baseUnitValue * 100) / 1e-9d, + ElectricResistivityUnit.NanoohmMeter => (baseUnitValue) / 1e-9d, + ElectricResistivityUnit.OhmCentimeter => baseUnitValue * 100, + ElectricResistivityUnit.OhmMeter => baseUnitValue, + ElectricResistivityUnit.PicoohmCentimeter => (baseUnitValue * 100) / 1e-12d, + ElectricResistivityUnit.PicoohmMeter => (baseUnitValue) / 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index b8c77c6120..e64988a04d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -132,57 +132,57 @@ public static ElectricSurfaceChargeDensity From(double value, ElectricSurfaceCha #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricSurfaceChargeDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ElectricSurfaceChargeDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter => _value * 1.0e4, - ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch => _value * 1.5500031000062000e3, - ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ElectricSurfaceChargeDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter => baseUnitValue / 1.0e4, - ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch => baseUnitValue / 1.5500031000062000e3, - ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ElectricSurfaceChargeDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ElectricSurfaceChargeDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter => _value * 1.0e4, + ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch => _value * 1.5500031000062000e3, + ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ElectricSurfaceChargeDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter => baseUnitValue / 1.0e4, + ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch => baseUnitValue / 1.5500031000062000e3, + ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Energy.g.cs index 45e0825101..7b5a48cd85 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Energy.g.cs @@ -514,127 +514,127 @@ public static Energy From(double value, EnergyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Energy ToUnit(EnergyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Energy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - EnergyUnit.BritishThermalUnit => _value * 1055.05585262, - EnergyUnit.Calorie => _value * 4.184, - EnergyUnit.DecathermEc => (_value * 1.05505585262e8) * 1e1d, - EnergyUnit.DecathermImperial => (_value * 1.05505585257348e8) * 1e1d, - EnergyUnit.DecathermUs => (_value * 1.054804e8) * 1e1d, - EnergyUnit.ElectronVolt => _value * 1.602176565e-19, - EnergyUnit.Erg => _value * 1e-7, - EnergyUnit.FootPound => _value * 1.355817948, - EnergyUnit.GigabritishThermalUnit => (_value * 1055.05585262) * 1e9d, - EnergyUnit.GigaelectronVolt => (_value * 1.602176565e-19) * 1e9d, - EnergyUnit.Gigajoule => (_value) * 1e9d, - EnergyUnit.GigawattDay => (_value * 24 * 3600d) * 1e9d, - EnergyUnit.GigawattHour => (_value * 3600d) * 1e9d, - EnergyUnit.HorsepowerHour => _value * 2.6845195377e6, - EnergyUnit.Joule => _value, - EnergyUnit.KilobritishThermalUnit => (_value * 1055.05585262) * 1e3d, - EnergyUnit.Kilocalorie => (_value * 4.184) * 1e3d, - EnergyUnit.KiloelectronVolt => (_value * 1.602176565e-19) * 1e3d, - EnergyUnit.Kilojoule => (_value) * 1e3d, - EnergyUnit.KilowattDay => (_value * 24 * 3600d) * 1e3d, - EnergyUnit.KilowattHour => (_value * 3600d) * 1e3d, - EnergyUnit.MegabritishThermalUnit => (_value * 1055.05585262) * 1e6d, - EnergyUnit.Megacalorie => (_value * 4.184) * 1e6d, - EnergyUnit.MegaelectronVolt => (_value * 1.602176565e-19) * 1e6d, - EnergyUnit.Megajoule => (_value) * 1e6d, - EnergyUnit.MegawattDay => (_value * 24 * 3600d) * 1e6d, - EnergyUnit.MegawattHour => (_value * 3600d) * 1e6d, - EnergyUnit.Millijoule => (_value) * 1e-3d, - EnergyUnit.Petajoule => (_value) * 1e15d, - EnergyUnit.TeraelectronVolt => (_value * 1.602176565e-19) * 1e12d, - EnergyUnit.Terajoule => (_value) * 1e12d, - EnergyUnit.TerawattDay => (_value * 24 * 3600d) * 1e12d, - EnergyUnit.TerawattHour => (_value * 3600d) * 1e12d, - EnergyUnit.ThermEc => _value * 1.05505585262e8, - EnergyUnit.ThermImperial => _value * 1.05505585257348e8, - EnergyUnit.ThermUs => _value * 1.054804e8, - EnergyUnit.WattDay => _value * 24 * 3600d, - EnergyUnit.WattHour => _value * 3600d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(EnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - EnergyUnit.BritishThermalUnit => baseUnitValue / 1055.05585262, - EnergyUnit.Calorie => baseUnitValue / 4.184, - EnergyUnit.DecathermEc => (baseUnitValue / 1.05505585262e8) / 1e1d, - EnergyUnit.DecathermImperial => (baseUnitValue / 1.05505585257348e8) / 1e1d, - EnergyUnit.DecathermUs => (baseUnitValue / 1.054804e8) / 1e1d, - EnergyUnit.ElectronVolt => baseUnitValue / 1.602176565e-19, - EnergyUnit.Erg => baseUnitValue / 1e-7, - EnergyUnit.FootPound => baseUnitValue / 1.355817948, - EnergyUnit.GigabritishThermalUnit => (baseUnitValue / 1055.05585262) / 1e9d, - EnergyUnit.GigaelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e9d, - EnergyUnit.Gigajoule => (baseUnitValue) / 1e9d, - EnergyUnit.GigawattDay => (baseUnitValue / (24 * 3600d)) / 1e9d, - EnergyUnit.GigawattHour => (baseUnitValue / 3600d) / 1e9d, - EnergyUnit.HorsepowerHour => baseUnitValue / 2.6845195377e6, - EnergyUnit.Joule => baseUnitValue, - EnergyUnit.KilobritishThermalUnit => (baseUnitValue / 1055.05585262) / 1e3d, - EnergyUnit.Kilocalorie => (baseUnitValue / 4.184) / 1e3d, - EnergyUnit.KiloelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e3d, - EnergyUnit.Kilojoule => (baseUnitValue) / 1e3d, - EnergyUnit.KilowattDay => (baseUnitValue / (24 * 3600d)) / 1e3d, - EnergyUnit.KilowattHour => (baseUnitValue / 3600d) / 1e3d, - EnergyUnit.MegabritishThermalUnit => (baseUnitValue / 1055.05585262) / 1e6d, - EnergyUnit.Megacalorie => (baseUnitValue / 4.184) / 1e6d, - EnergyUnit.MegaelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e6d, - EnergyUnit.Megajoule => (baseUnitValue) / 1e6d, - EnergyUnit.MegawattDay => (baseUnitValue / (24 * 3600d)) / 1e6d, - EnergyUnit.MegawattHour => (baseUnitValue / 3600d) / 1e6d, - EnergyUnit.Millijoule => (baseUnitValue) / 1e-3d, - EnergyUnit.Petajoule => (baseUnitValue) / 1e15d, - EnergyUnit.TeraelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e12d, - EnergyUnit.Terajoule => (baseUnitValue) / 1e12d, - EnergyUnit.TerawattDay => (baseUnitValue / (24 * 3600d)) / 1e12d, - EnergyUnit.TerawattHour => (baseUnitValue / 3600d) / 1e12d, - EnergyUnit.ThermEc => baseUnitValue / 1.05505585262e8, - EnergyUnit.ThermImperial => baseUnitValue / 1.05505585257348e8, - EnergyUnit.ThermUs => baseUnitValue / 1.054804e8, - EnergyUnit.WattDay => baseUnitValue / (24 * 3600d), - EnergyUnit.WattHour => baseUnitValue / 3600d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(EnergyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Energy ToUnit(EnergyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Energy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + EnergyUnit.BritishThermalUnit => _value * 1055.05585262, + EnergyUnit.Calorie => _value * 4.184, + EnergyUnit.DecathermEc => (_value * 1.05505585262e8) * 1e1d, + EnergyUnit.DecathermImperial => (_value * 1.05505585257348e8) * 1e1d, + EnergyUnit.DecathermUs => (_value * 1.054804e8) * 1e1d, + EnergyUnit.ElectronVolt => _value * 1.602176565e-19, + EnergyUnit.Erg => _value * 1e-7, + EnergyUnit.FootPound => _value * 1.355817948, + EnergyUnit.GigabritishThermalUnit => (_value * 1055.05585262) * 1e9d, + EnergyUnit.GigaelectronVolt => (_value * 1.602176565e-19) * 1e9d, + EnergyUnit.Gigajoule => (_value) * 1e9d, + EnergyUnit.GigawattDay => (_value * 24 * 3600d) * 1e9d, + EnergyUnit.GigawattHour => (_value * 3600d) * 1e9d, + EnergyUnit.HorsepowerHour => _value * 2.6845195377e6, + EnergyUnit.Joule => _value, + EnergyUnit.KilobritishThermalUnit => (_value * 1055.05585262) * 1e3d, + EnergyUnit.Kilocalorie => (_value * 4.184) * 1e3d, + EnergyUnit.KiloelectronVolt => (_value * 1.602176565e-19) * 1e3d, + EnergyUnit.Kilojoule => (_value) * 1e3d, + EnergyUnit.KilowattDay => (_value * 24 * 3600d) * 1e3d, + EnergyUnit.KilowattHour => (_value * 3600d) * 1e3d, + EnergyUnit.MegabritishThermalUnit => (_value * 1055.05585262) * 1e6d, + EnergyUnit.Megacalorie => (_value * 4.184) * 1e6d, + EnergyUnit.MegaelectronVolt => (_value * 1.602176565e-19) * 1e6d, + EnergyUnit.Megajoule => (_value) * 1e6d, + EnergyUnit.MegawattDay => (_value * 24 * 3600d) * 1e6d, + EnergyUnit.MegawattHour => (_value * 3600d) * 1e6d, + EnergyUnit.Millijoule => (_value) * 1e-3d, + EnergyUnit.Petajoule => (_value) * 1e15d, + EnergyUnit.TeraelectronVolt => (_value * 1.602176565e-19) * 1e12d, + EnergyUnit.Terajoule => (_value) * 1e12d, + EnergyUnit.TerawattDay => (_value * 24 * 3600d) * 1e12d, + EnergyUnit.TerawattHour => (_value * 3600d) * 1e12d, + EnergyUnit.ThermEc => _value * 1.05505585262e8, + EnergyUnit.ThermImperial => _value * 1.05505585257348e8, + EnergyUnit.ThermUs => _value * 1.054804e8, + EnergyUnit.WattDay => _value * 24 * 3600d, + EnergyUnit.WattHour => _value * 3600d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(EnergyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + EnergyUnit.BritishThermalUnit => baseUnitValue / 1055.05585262, + EnergyUnit.Calorie => baseUnitValue / 4.184, + EnergyUnit.DecathermEc => (baseUnitValue / 1.05505585262e8) / 1e1d, + EnergyUnit.DecathermImperial => (baseUnitValue / 1.05505585257348e8) / 1e1d, + EnergyUnit.DecathermUs => (baseUnitValue / 1.054804e8) / 1e1d, + EnergyUnit.ElectronVolt => baseUnitValue / 1.602176565e-19, + EnergyUnit.Erg => baseUnitValue / 1e-7, + EnergyUnit.FootPound => baseUnitValue / 1.355817948, + EnergyUnit.GigabritishThermalUnit => (baseUnitValue / 1055.05585262) / 1e9d, + EnergyUnit.GigaelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e9d, + EnergyUnit.Gigajoule => (baseUnitValue) / 1e9d, + EnergyUnit.GigawattDay => (baseUnitValue / (24 * 3600d)) / 1e9d, + EnergyUnit.GigawattHour => (baseUnitValue / 3600d) / 1e9d, + EnergyUnit.HorsepowerHour => baseUnitValue / 2.6845195377e6, + EnergyUnit.Joule => baseUnitValue, + EnergyUnit.KilobritishThermalUnit => (baseUnitValue / 1055.05585262) / 1e3d, + EnergyUnit.Kilocalorie => (baseUnitValue / 4.184) / 1e3d, + EnergyUnit.KiloelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e3d, + EnergyUnit.Kilojoule => (baseUnitValue) / 1e3d, + EnergyUnit.KilowattDay => (baseUnitValue / (24 * 3600d)) / 1e3d, + EnergyUnit.KilowattHour => (baseUnitValue / 3600d) / 1e3d, + EnergyUnit.MegabritishThermalUnit => (baseUnitValue / 1055.05585262) / 1e6d, + EnergyUnit.Megacalorie => (baseUnitValue / 4.184) / 1e6d, + EnergyUnit.MegaelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e6d, + EnergyUnit.Megajoule => (baseUnitValue) / 1e6d, + EnergyUnit.MegawattDay => (baseUnitValue / (24 * 3600d)) / 1e6d, + EnergyUnit.MegawattHour => (baseUnitValue / 3600d) / 1e6d, + EnergyUnit.Millijoule => (baseUnitValue) / 1e-3d, + EnergyUnit.Petajoule => (baseUnitValue) / 1e15d, + EnergyUnit.TeraelectronVolt => (baseUnitValue / 1.602176565e-19) / 1e12d, + EnergyUnit.Terajoule => (baseUnitValue) / 1e12d, + EnergyUnit.TerawattDay => (baseUnitValue / (24 * 3600d)) / 1e12d, + EnergyUnit.TerawattHour => (baseUnitValue / 3600d) / 1e12d, + EnergyUnit.ThermEc => baseUnitValue / 1.05505585262e8, + EnergyUnit.ThermImperial => baseUnitValue / 1.05505585257348e8, + EnergyUnit.ThermUs => baseUnitValue / 1.054804e8, + EnergyUnit.WattDay => baseUnitValue / (24 * 3600d), + EnergyUnit.WattHour => baseUnitValue / 3600d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/EnergyDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/EnergyDensity.g.cs index aebb204f4a..541565625c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/EnergyDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/EnergyDensity.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// Energy density is the amount of energy stored in a substance per unit volume and is measured in J/m³. It is sometimes confused with energy per unit mass which is properly called specific energy. + /// /// public struct EnergyDensity { @@ -228,75 +228,75 @@ public static EnergyDensity From(double value, EnergyDensityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public EnergyDensity ToUnit(EnergyDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new EnergyDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - EnergyDensityUnit.GigajoulePerCubicMeter => (_value) * 1e9d, - EnergyDensityUnit.GigawattHourPerCubicMeter => (_value * 3.6e+3) * 1e9d, - EnergyDensityUnit.JoulePerCubicMeter => _value, - EnergyDensityUnit.KilojoulePerCubicMeter => (_value) * 1e3d, - EnergyDensityUnit.KilowattHourPerCubicMeter => (_value * 3.6e+3) * 1e3d, - EnergyDensityUnit.MegajoulePerCubicMeter => (_value) * 1e6d, - EnergyDensityUnit.MegawattHourPerCubicMeter => (_value * 3.6e+3) * 1e6d, - EnergyDensityUnit.PetajoulePerCubicMeter => (_value) * 1e15d, - EnergyDensityUnit.PetawattHourPerCubicMeter => (_value * 3.6e+3) * 1e15d, - EnergyDensityUnit.TerajoulePerCubicMeter => (_value) * 1e12d, - EnergyDensityUnit.TerawattHourPerCubicMeter => (_value * 3.6e+3) * 1e12d, - EnergyDensityUnit.WattHourPerCubicMeter => _value * 3.6e+3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(EnergyDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - EnergyDensityUnit.GigajoulePerCubicMeter => (baseUnitValue) / 1e9d, - EnergyDensityUnit.GigawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e9d, - EnergyDensityUnit.JoulePerCubicMeter => baseUnitValue, - EnergyDensityUnit.KilojoulePerCubicMeter => (baseUnitValue) / 1e3d, - EnergyDensityUnit.KilowattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e3d, - EnergyDensityUnit.MegajoulePerCubicMeter => (baseUnitValue) / 1e6d, - EnergyDensityUnit.MegawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e6d, - EnergyDensityUnit.PetajoulePerCubicMeter => (baseUnitValue) / 1e15d, - EnergyDensityUnit.PetawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e15d, - EnergyDensityUnit.TerajoulePerCubicMeter => (baseUnitValue) / 1e12d, - EnergyDensityUnit.TerawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e12d, - EnergyDensityUnit.WattHourPerCubicMeter => baseUnitValue / 3.6e+3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(EnergyDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public EnergyDensity ToUnit(EnergyDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new EnergyDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + EnergyDensityUnit.GigajoulePerCubicMeter => (_value) * 1e9d, + EnergyDensityUnit.GigawattHourPerCubicMeter => (_value * 3.6e+3) * 1e9d, + EnergyDensityUnit.JoulePerCubicMeter => _value, + EnergyDensityUnit.KilojoulePerCubicMeter => (_value) * 1e3d, + EnergyDensityUnit.KilowattHourPerCubicMeter => (_value * 3.6e+3) * 1e3d, + EnergyDensityUnit.MegajoulePerCubicMeter => (_value) * 1e6d, + EnergyDensityUnit.MegawattHourPerCubicMeter => (_value * 3.6e+3) * 1e6d, + EnergyDensityUnit.PetajoulePerCubicMeter => (_value) * 1e15d, + EnergyDensityUnit.PetawattHourPerCubicMeter => (_value * 3.6e+3) * 1e15d, + EnergyDensityUnit.TerajoulePerCubicMeter => (_value) * 1e12d, + EnergyDensityUnit.TerawattHourPerCubicMeter => (_value * 3.6e+3) * 1e12d, + EnergyDensityUnit.WattHourPerCubicMeter => _value * 3.6e+3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(EnergyDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + EnergyDensityUnit.GigajoulePerCubicMeter => (baseUnitValue) / 1e9d, + EnergyDensityUnit.GigawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e9d, + EnergyDensityUnit.JoulePerCubicMeter => baseUnitValue, + EnergyDensityUnit.KilojoulePerCubicMeter => (baseUnitValue) / 1e3d, + EnergyDensityUnit.KilowattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e3d, + EnergyDensityUnit.MegajoulePerCubicMeter => (baseUnitValue) / 1e6d, + EnergyDensityUnit.MegawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e6d, + EnergyDensityUnit.PetajoulePerCubicMeter => (baseUnitValue) / 1e15d, + EnergyDensityUnit.PetawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e15d, + EnergyDensityUnit.TerajoulePerCubicMeter => (baseUnitValue) / 1e12d, + EnergyDensityUnit.TerawattHourPerCubicMeter => (baseUnitValue / 3.6e+3) / 1e12d, + EnergyDensityUnit.WattHourPerCubicMeter => baseUnitValue / 3.6e+3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Entropy.g.cs index e16a5a34fd..b16ca07cca 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Entropy.g.cs @@ -173,65 +173,65 @@ public static Entropy From(double value, EntropyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EntropyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Entropy ToUnit(EntropyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Entropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - EntropyUnit.CaloriePerKelvin => _value * 4.184, - EntropyUnit.JoulePerDegreeCelsius => _value, - EntropyUnit.JoulePerKelvin => _value, - EntropyUnit.KilocaloriePerKelvin => (_value * 4.184) * 1e3d, - EntropyUnit.KilojoulePerDegreeCelsius => (_value) * 1e3d, - EntropyUnit.KilojoulePerKelvin => (_value) * 1e3d, - EntropyUnit.MegajoulePerKelvin => (_value) * 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(EntropyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - EntropyUnit.CaloriePerKelvin => baseUnitValue / 4.184, - EntropyUnit.JoulePerDegreeCelsius => baseUnitValue, - EntropyUnit.JoulePerKelvin => baseUnitValue, - EntropyUnit.KilocaloriePerKelvin => (baseUnitValue / 4.184) / 1e3d, - EntropyUnit.KilojoulePerDegreeCelsius => (baseUnitValue) / 1e3d, - EntropyUnit.KilojoulePerKelvin => (baseUnitValue) / 1e3d, - EntropyUnit.MegajoulePerKelvin => (baseUnitValue) / 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(EntropyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Entropy ToUnit(EntropyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Entropy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + EntropyUnit.CaloriePerKelvin => _value * 4.184, + EntropyUnit.JoulePerDegreeCelsius => _value, + EntropyUnit.JoulePerKelvin => _value, + EntropyUnit.KilocaloriePerKelvin => (_value * 4.184) * 1e3d, + EntropyUnit.KilojoulePerDegreeCelsius => (_value) * 1e3d, + EntropyUnit.KilojoulePerKelvin => (_value) * 1e3d, + EntropyUnit.MegajoulePerKelvin => (_value) * 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(EntropyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + EntropyUnit.CaloriePerKelvin => baseUnitValue / 4.184, + EntropyUnit.JoulePerDegreeCelsius => baseUnitValue, + EntropyUnit.JoulePerKelvin => baseUnitValue, + EntropyUnit.KilocaloriePerKelvin => (baseUnitValue / 4.184) / 1e3d, + EntropyUnit.KilojoulePerDegreeCelsius => (baseUnitValue) / 1e3d, + EntropyUnit.KilojoulePerKelvin => (baseUnitValue) / 1e3d, + EntropyUnit.MegajoulePerKelvin => (baseUnitValue) / 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Force.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Force.g.cs index 3a12234508..94aad2c4e7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Force.g.cs @@ -261,81 +261,81 @@ public static Force From(double value, ForceUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Force ToUnit(ForceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Force(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ForceUnit.Decanewton => (_value) * 1e1d, - ForceUnit.Dyn => _value / 1e5, - ForceUnit.KilogramForce => _value * 9.80665002864, - ForceUnit.Kilonewton => (_value) * 1e3d, - ForceUnit.KiloPond => _value * 9.80665002864, - ForceUnit.KilopoundForce => (_value * 4.4482216152605095551842641431421) * 1e3d, - ForceUnit.Meganewton => (_value) * 1e6d, - ForceUnit.Micronewton => (_value) * 1e-6d, - ForceUnit.Millinewton => (_value) * 1e-3d, - ForceUnit.Newton => _value, - ForceUnit.OunceForce => _value * 2.780138509537812e-1, - ForceUnit.Poundal => _value * 0.13825502798973041652092282466083, - ForceUnit.PoundForce => _value * 4.4482216152605095551842641431421, - ForceUnit.ShortTonForce => _value * 8.896443230521e3, - ForceUnit.TonneForce => _value * 9.80665002864e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ForceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ForceUnit.Decanewton => (baseUnitValue) / 1e1d, - ForceUnit.Dyn => baseUnitValue * 1e5, - ForceUnit.KilogramForce => baseUnitValue / 9.80665002864, - ForceUnit.Kilonewton => (baseUnitValue) / 1e3d, - ForceUnit.KiloPond => baseUnitValue / 9.80665002864, - ForceUnit.KilopoundForce => (baseUnitValue / 4.4482216152605095551842641431421) / 1e3d, - ForceUnit.Meganewton => (baseUnitValue) / 1e6d, - ForceUnit.Micronewton => (baseUnitValue) / 1e-6d, - ForceUnit.Millinewton => (baseUnitValue) / 1e-3d, - ForceUnit.Newton => baseUnitValue, - ForceUnit.OunceForce => baseUnitValue / 2.780138509537812e-1, - ForceUnit.Poundal => baseUnitValue / 0.13825502798973041652092282466083, - ForceUnit.PoundForce => baseUnitValue / 4.4482216152605095551842641431421, - ForceUnit.ShortTonForce => baseUnitValue / 8.896443230521e3, - ForceUnit.TonneForce => baseUnitValue / 9.80665002864e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Force ToUnit(ForceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Force(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ForceUnit.Decanewton => (_value) * 1e1d, + ForceUnit.Dyn => _value / 1e5, + ForceUnit.KilogramForce => _value * 9.80665002864, + ForceUnit.Kilonewton => (_value) * 1e3d, + ForceUnit.KiloPond => _value * 9.80665002864, + ForceUnit.KilopoundForce => (_value * 4.4482216152605095551842641431421) * 1e3d, + ForceUnit.Meganewton => (_value) * 1e6d, + ForceUnit.Micronewton => (_value) * 1e-6d, + ForceUnit.Millinewton => (_value) * 1e-3d, + ForceUnit.Newton => _value, + ForceUnit.OunceForce => _value * 2.780138509537812e-1, + ForceUnit.Poundal => _value * 0.13825502798973041652092282466083, + ForceUnit.PoundForce => _value * 4.4482216152605095551842641431421, + ForceUnit.ShortTonForce => _value * 8.896443230521e3, + ForceUnit.TonneForce => _value * 9.80665002864e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ForceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ForceUnit.Decanewton => (baseUnitValue) / 1e1d, + ForceUnit.Dyn => baseUnitValue * 1e5, + ForceUnit.KilogramForce => baseUnitValue / 9.80665002864, + ForceUnit.Kilonewton => (baseUnitValue) / 1e3d, + ForceUnit.KiloPond => baseUnitValue / 9.80665002864, + ForceUnit.KilopoundForce => (baseUnitValue / 4.4482216152605095551842641431421) / 1e3d, + ForceUnit.Meganewton => (baseUnitValue) / 1e6d, + ForceUnit.Micronewton => (baseUnitValue) / 1e-6d, + ForceUnit.Millinewton => (baseUnitValue) / 1e-3d, + ForceUnit.Newton => baseUnitValue, + ForceUnit.OunceForce => baseUnitValue / 2.780138509537812e-1, + ForceUnit.Poundal => baseUnitValue / 0.13825502798973041652092282466083, + ForceUnit.PoundForce => baseUnitValue / 4.4482216152605095551842641431421, + ForceUnit.ShortTonForce => baseUnitValue / 8.896443230521e3, + ForceUnit.TonneForce => baseUnitValue / 9.80665002864e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForceChangeRate.g.cs index 5c0f2a225f..3bb1e2804b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -261,81 +261,81 @@ public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceChangeRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ForceChangeRate ToUnit(ForceChangeRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ForceChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ForceChangeRateUnit.CentinewtonPerSecond => (_value) * 1e-2d, - ForceChangeRateUnit.DecanewtonPerMinute => (_value / 60) * 1e1d, - ForceChangeRateUnit.DecanewtonPerSecond => (_value) * 1e1d, - ForceChangeRateUnit.DecinewtonPerSecond => (_value) * 1e-1d, - ForceChangeRateUnit.KilonewtonPerMinute => (_value / 60) * 1e3d, - ForceChangeRateUnit.KilonewtonPerSecond => (_value) * 1e3d, - ForceChangeRateUnit.KilopoundForcePerMinute => (_value * 4.4482216152605095551842641431421 / 60) * 1e3d, - ForceChangeRateUnit.KilopoundForcePerSecond => (_value * 4.4482216152605095551842641431421) * 1e3d, - ForceChangeRateUnit.MicronewtonPerSecond => (_value) * 1e-6d, - ForceChangeRateUnit.MillinewtonPerSecond => (_value) * 1e-3d, - ForceChangeRateUnit.NanonewtonPerSecond => (_value) * 1e-9d, - ForceChangeRateUnit.NewtonPerMinute => _value / 60, - ForceChangeRateUnit.NewtonPerSecond => _value, - ForceChangeRateUnit.PoundForcePerMinute => _value * 4.4482216152605095551842641431421 / 60, - ForceChangeRateUnit.PoundForcePerSecond => _value * 4.4482216152605095551842641431421, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ForceChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ForceChangeRateUnit.CentinewtonPerSecond => (baseUnitValue) / 1e-2d, - ForceChangeRateUnit.DecanewtonPerMinute => (baseUnitValue * 60) / 1e1d, - ForceChangeRateUnit.DecanewtonPerSecond => (baseUnitValue) / 1e1d, - ForceChangeRateUnit.DecinewtonPerSecond => (baseUnitValue) / 1e-1d, - ForceChangeRateUnit.KilonewtonPerMinute => (baseUnitValue * 60) / 1e3d, - ForceChangeRateUnit.KilonewtonPerSecond => (baseUnitValue) / 1e3d, - ForceChangeRateUnit.KilopoundForcePerMinute => (baseUnitValue / 4.4482216152605095551842641431421 * 60) / 1e3d, - ForceChangeRateUnit.KilopoundForcePerSecond => (baseUnitValue / 4.4482216152605095551842641431421) / 1e3d, - ForceChangeRateUnit.MicronewtonPerSecond => (baseUnitValue) / 1e-6d, - ForceChangeRateUnit.MillinewtonPerSecond => (baseUnitValue) / 1e-3d, - ForceChangeRateUnit.NanonewtonPerSecond => (baseUnitValue) / 1e-9d, - ForceChangeRateUnit.NewtonPerMinute => baseUnitValue * 60, - ForceChangeRateUnit.NewtonPerSecond => baseUnitValue, - ForceChangeRateUnit.PoundForcePerMinute => baseUnitValue / 4.4482216152605095551842641431421 * 60, - ForceChangeRateUnit.PoundForcePerSecond => baseUnitValue / 4.4482216152605095551842641431421, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForceChangeRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ForceChangeRate ToUnit(ForceChangeRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ForceChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ForceChangeRateUnit.CentinewtonPerSecond => (_value) * 1e-2d, + ForceChangeRateUnit.DecanewtonPerMinute => (_value / 60) * 1e1d, + ForceChangeRateUnit.DecanewtonPerSecond => (_value) * 1e1d, + ForceChangeRateUnit.DecinewtonPerSecond => (_value) * 1e-1d, + ForceChangeRateUnit.KilonewtonPerMinute => (_value / 60) * 1e3d, + ForceChangeRateUnit.KilonewtonPerSecond => (_value) * 1e3d, + ForceChangeRateUnit.KilopoundForcePerMinute => (_value * 4.4482216152605095551842641431421 / 60) * 1e3d, + ForceChangeRateUnit.KilopoundForcePerSecond => (_value * 4.4482216152605095551842641431421) * 1e3d, + ForceChangeRateUnit.MicronewtonPerSecond => (_value) * 1e-6d, + ForceChangeRateUnit.MillinewtonPerSecond => (_value) * 1e-3d, + ForceChangeRateUnit.NanonewtonPerSecond => (_value) * 1e-9d, + ForceChangeRateUnit.NewtonPerMinute => _value / 60, + ForceChangeRateUnit.NewtonPerSecond => _value, + ForceChangeRateUnit.PoundForcePerMinute => _value * 4.4482216152605095551842641431421 / 60, + ForceChangeRateUnit.PoundForcePerSecond => _value * 4.4482216152605095551842641431421, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ForceChangeRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ForceChangeRateUnit.CentinewtonPerSecond => (baseUnitValue) / 1e-2d, + ForceChangeRateUnit.DecanewtonPerMinute => (baseUnitValue * 60) / 1e1d, + ForceChangeRateUnit.DecanewtonPerSecond => (baseUnitValue) / 1e1d, + ForceChangeRateUnit.DecinewtonPerSecond => (baseUnitValue) / 1e-1d, + ForceChangeRateUnit.KilonewtonPerMinute => (baseUnitValue * 60) / 1e3d, + ForceChangeRateUnit.KilonewtonPerSecond => (baseUnitValue) / 1e3d, + ForceChangeRateUnit.KilopoundForcePerMinute => (baseUnitValue / 4.4482216152605095551842641431421 * 60) / 1e3d, + ForceChangeRateUnit.KilopoundForcePerSecond => (baseUnitValue / 4.4482216152605095551842641431421) / 1e3d, + ForceChangeRateUnit.MicronewtonPerSecond => (baseUnitValue) / 1e-6d, + ForceChangeRateUnit.MillinewtonPerSecond => (baseUnitValue) / 1e-3d, + ForceChangeRateUnit.NanonewtonPerSecond => (baseUnitValue) / 1e-9d, + ForceChangeRateUnit.NewtonPerMinute => baseUnitValue * 60, + ForceChangeRateUnit.NewtonPerSecond => baseUnitValue, + ForceChangeRateUnit.PoundForcePerMinute => baseUnitValue / 4.4482216152605095551842641431421 * 60, + ForceChangeRateUnit.PoundForcePerSecond => baseUnitValue / 4.4482216152605095551842641431421, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForcePerLength.g.cs index 0ac94381ac..8184e027d1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -514,127 +514,127 @@ public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForcePerLengthUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ForcePerLength ToUnit(ForcePerLengthUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ForcePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ForcePerLengthUnit.CentinewtonPerCentimeter => (_value * 1e2) * 1e-2d, - ForcePerLengthUnit.CentinewtonPerMeter => (_value) * 1e-2d, - ForcePerLengthUnit.CentinewtonPerMillimeter => (_value * 1e3) * 1e-2d, - ForcePerLengthUnit.DecanewtonPerCentimeter => (_value * 1e2) * 1e1d, - ForcePerLengthUnit.DecanewtonPerMeter => (_value) * 1e1d, - ForcePerLengthUnit.DecanewtonPerMillimeter => (_value * 1e3) * 1e1d, - ForcePerLengthUnit.DecinewtonPerCentimeter => (_value * 1e2) * 1e-1d, - ForcePerLengthUnit.DecinewtonPerMeter => (_value) * 1e-1d, - ForcePerLengthUnit.DecinewtonPerMillimeter => (_value * 1e3) * 1e-1d, - ForcePerLengthUnit.KilogramForcePerCentimeter => _value * 980.665002864, - ForcePerLengthUnit.KilogramForcePerMeter => _value * 9.80665002864, - ForcePerLengthUnit.KilogramForcePerMillimeter => _value * 9.80665002864e3, - ForcePerLengthUnit.KilonewtonPerCentimeter => (_value * 1e2) * 1e3d, - ForcePerLengthUnit.KilonewtonPerMeter => (_value) * 1e3d, - ForcePerLengthUnit.KilonewtonPerMillimeter => (_value * 1e3) * 1e3d, - ForcePerLengthUnit.KilopoundForcePerFoot => _value * 14593.90292, - ForcePerLengthUnit.KilopoundForcePerInch => _value * 1.75126835e5, - ForcePerLengthUnit.MeganewtonPerCentimeter => (_value * 1e2) * 1e6d, - ForcePerLengthUnit.MeganewtonPerMeter => (_value) * 1e6d, - ForcePerLengthUnit.MeganewtonPerMillimeter => (_value * 1e3) * 1e6d, - ForcePerLengthUnit.MicronewtonPerCentimeter => (_value * 1e2) * 1e-6d, - ForcePerLengthUnit.MicronewtonPerMeter => (_value) * 1e-6d, - ForcePerLengthUnit.MicronewtonPerMillimeter => (_value * 1e3) * 1e-6d, - ForcePerLengthUnit.MillinewtonPerCentimeter => (_value * 1e2) * 1e-3d, - ForcePerLengthUnit.MillinewtonPerMeter => (_value) * 1e-3d, - ForcePerLengthUnit.MillinewtonPerMillimeter => (_value * 1e3) * 1e-3d, - ForcePerLengthUnit.NanonewtonPerCentimeter => (_value * 1e2) * 1e-9d, - ForcePerLengthUnit.NanonewtonPerMeter => (_value) * 1e-9d, - ForcePerLengthUnit.NanonewtonPerMillimeter => (_value * 1e3) * 1e-9d, - ForcePerLengthUnit.NewtonPerCentimeter => _value * 1e2, - ForcePerLengthUnit.NewtonPerMeter => _value, - ForcePerLengthUnit.NewtonPerMillimeter => _value * 1e3, - ForcePerLengthUnit.PoundForcePerFoot => _value * 14.59390292, - ForcePerLengthUnit.PoundForcePerInch => _value * 1.75126835e2, - ForcePerLengthUnit.PoundForcePerYard => _value * 4.864634307, - ForcePerLengthUnit.TonneForcePerCentimeter => _value * 9.80665002864e5, - ForcePerLengthUnit.TonneForcePerMeter => _value * 9.80665002864e3, - ForcePerLengthUnit.TonneForcePerMillimeter => _value * 9.80665002864e6, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ForcePerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ForcePerLengthUnit.CentinewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-2d, - ForcePerLengthUnit.CentinewtonPerMeter => (baseUnitValue) / 1e-2d, - ForcePerLengthUnit.CentinewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-2d, - ForcePerLengthUnit.DecanewtonPerCentimeter => (baseUnitValue / 1e2) / 1e1d, - ForcePerLengthUnit.DecanewtonPerMeter => (baseUnitValue) / 1e1d, - ForcePerLengthUnit.DecanewtonPerMillimeter => (baseUnitValue / 1e3) / 1e1d, - ForcePerLengthUnit.DecinewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-1d, - ForcePerLengthUnit.DecinewtonPerMeter => (baseUnitValue) / 1e-1d, - ForcePerLengthUnit.DecinewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-1d, - ForcePerLengthUnit.KilogramForcePerCentimeter => baseUnitValue / 980.665002864, - ForcePerLengthUnit.KilogramForcePerMeter => baseUnitValue / 9.80665002864, - ForcePerLengthUnit.KilogramForcePerMillimeter => baseUnitValue / 9.80665002864e3, - ForcePerLengthUnit.KilonewtonPerCentimeter => (baseUnitValue / 1e2) / 1e3d, - ForcePerLengthUnit.KilonewtonPerMeter => (baseUnitValue) / 1e3d, - ForcePerLengthUnit.KilonewtonPerMillimeter => (baseUnitValue / 1e3) / 1e3d, - ForcePerLengthUnit.KilopoundForcePerFoot => baseUnitValue / 14593.90292, - ForcePerLengthUnit.KilopoundForcePerInch => baseUnitValue / 1.75126835e5, - ForcePerLengthUnit.MeganewtonPerCentimeter => (baseUnitValue / 1e2) / 1e6d, - ForcePerLengthUnit.MeganewtonPerMeter => (baseUnitValue) / 1e6d, - ForcePerLengthUnit.MeganewtonPerMillimeter => (baseUnitValue / 1e3) / 1e6d, - ForcePerLengthUnit.MicronewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-6d, - ForcePerLengthUnit.MicronewtonPerMeter => (baseUnitValue) / 1e-6d, - ForcePerLengthUnit.MicronewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-6d, - ForcePerLengthUnit.MillinewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-3d, - ForcePerLengthUnit.MillinewtonPerMeter => (baseUnitValue) / 1e-3d, - ForcePerLengthUnit.MillinewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-3d, - ForcePerLengthUnit.NanonewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-9d, - ForcePerLengthUnit.NanonewtonPerMeter => (baseUnitValue) / 1e-9d, - ForcePerLengthUnit.NanonewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-9d, - ForcePerLengthUnit.NewtonPerCentimeter => baseUnitValue / 1e2, - ForcePerLengthUnit.NewtonPerMeter => baseUnitValue, - ForcePerLengthUnit.NewtonPerMillimeter => baseUnitValue / 1e3, - ForcePerLengthUnit.PoundForcePerFoot => baseUnitValue / 14.59390292, - ForcePerLengthUnit.PoundForcePerInch => baseUnitValue / 1.75126835e2, - ForcePerLengthUnit.PoundForcePerYard => baseUnitValue / 4.864634307, - ForcePerLengthUnit.TonneForcePerCentimeter => baseUnitValue / 9.80665002864e5, - ForcePerLengthUnit.TonneForcePerMeter => baseUnitValue / 9.80665002864e3, - ForcePerLengthUnit.TonneForcePerMillimeter => baseUnitValue / 9.80665002864e6, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ForcePerLengthUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ForcePerLength ToUnit(ForcePerLengthUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ForcePerLength(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ForcePerLengthUnit.CentinewtonPerCentimeter => (_value * 1e2) * 1e-2d, + ForcePerLengthUnit.CentinewtonPerMeter => (_value) * 1e-2d, + ForcePerLengthUnit.CentinewtonPerMillimeter => (_value * 1e3) * 1e-2d, + ForcePerLengthUnit.DecanewtonPerCentimeter => (_value * 1e2) * 1e1d, + ForcePerLengthUnit.DecanewtonPerMeter => (_value) * 1e1d, + ForcePerLengthUnit.DecanewtonPerMillimeter => (_value * 1e3) * 1e1d, + ForcePerLengthUnit.DecinewtonPerCentimeter => (_value * 1e2) * 1e-1d, + ForcePerLengthUnit.DecinewtonPerMeter => (_value) * 1e-1d, + ForcePerLengthUnit.DecinewtonPerMillimeter => (_value * 1e3) * 1e-1d, + ForcePerLengthUnit.KilogramForcePerCentimeter => _value * 980.665002864, + ForcePerLengthUnit.KilogramForcePerMeter => _value * 9.80665002864, + ForcePerLengthUnit.KilogramForcePerMillimeter => _value * 9.80665002864e3, + ForcePerLengthUnit.KilonewtonPerCentimeter => (_value * 1e2) * 1e3d, + ForcePerLengthUnit.KilonewtonPerMeter => (_value) * 1e3d, + ForcePerLengthUnit.KilonewtonPerMillimeter => (_value * 1e3) * 1e3d, + ForcePerLengthUnit.KilopoundForcePerFoot => _value * 14593.90292, + ForcePerLengthUnit.KilopoundForcePerInch => _value * 1.75126835e5, + ForcePerLengthUnit.MeganewtonPerCentimeter => (_value * 1e2) * 1e6d, + ForcePerLengthUnit.MeganewtonPerMeter => (_value) * 1e6d, + ForcePerLengthUnit.MeganewtonPerMillimeter => (_value * 1e3) * 1e6d, + ForcePerLengthUnit.MicronewtonPerCentimeter => (_value * 1e2) * 1e-6d, + ForcePerLengthUnit.MicronewtonPerMeter => (_value) * 1e-6d, + ForcePerLengthUnit.MicronewtonPerMillimeter => (_value * 1e3) * 1e-6d, + ForcePerLengthUnit.MillinewtonPerCentimeter => (_value * 1e2) * 1e-3d, + ForcePerLengthUnit.MillinewtonPerMeter => (_value) * 1e-3d, + ForcePerLengthUnit.MillinewtonPerMillimeter => (_value * 1e3) * 1e-3d, + ForcePerLengthUnit.NanonewtonPerCentimeter => (_value * 1e2) * 1e-9d, + ForcePerLengthUnit.NanonewtonPerMeter => (_value) * 1e-9d, + ForcePerLengthUnit.NanonewtonPerMillimeter => (_value * 1e3) * 1e-9d, + ForcePerLengthUnit.NewtonPerCentimeter => _value * 1e2, + ForcePerLengthUnit.NewtonPerMeter => _value, + ForcePerLengthUnit.NewtonPerMillimeter => _value * 1e3, + ForcePerLengthUnit.PoundForcePerFoot => _value * 14.59390292, + ForcePerLengthUnit.PoundForcePerInch => _value * 1.75126835e2, + ForcePerLengthUnit.PoundForcePerYard => _value * 4.864634307, + ForcePerLengthUnit.TonneForcePerCentimeter => _value * 9.80665002864e5, + ForcePerLengthUnit.TonneForcePerMeter => _value * 9.80665002864e3, + ForcePerLengthUnit.TonneForcePerMillimeter => _value * 9.80665002864e6, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ForcePerLengthUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ForcePerLengthUnit.CentinewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-2d, + ForcePerLengthUnit.CentinewtonPerMeter => (baseUnitValue) / 1e-2d, + ForcePerLengthUnit.CentinewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-2d, + ForcePerLengthUnit.DecanewtonPerCentimeter => (baseUnitValue / 1e2) / 1e1d, + ForcePerLengthUnit.DecanewtonPerMeter => (baseUnitValue) / 1e1d, + ForcePerLengthUnit.DecanewtonPerMillimeter => (baseUnitValue / 1e3) / 1e1d, + ForcePerLengthUnit.DecinewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-1d, + ForcePerLengthUnit.DecinewtonPerMeter => (baseUnitValue) / 1e-1d, + ForcePerLengthUnit.DecinewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-1d, + ForcePerLengthUnit.KilogramForcePerCentimeter => baseUnitValue / 980.665002864, + ForcePerLengthUnit.KilogramForcePerMeter => baseUnitValue / 9.80665002864, + ForcePerLengthUnit.KilogramForcePerMillimeter => baseUnitValue / 9.80665002864e3, + ForcePerLengthUnit.KilonewtonPerCentimeter => (baseUnitValue / 1e2) / 1e3d, + ForcePerLengthUnit.KilonewtonPerMeter => (baseUnitValue) / 1e3d, + ForcePerLengthUnit.KilonewtonPerMillimeter => (baseUnitValue / 1e3) / 1e3d, + ForcePerLengthUnit.KilopoundForcePerFoot => baseUnitValue / 14593.90292, + ForcePerLengthUnit.KilopoundForcePerInch => baseUnitValue / 1.75126835e5, + ForcePerLengthUnit.MeganewtonPerCentimeter => (baseUnitValue / 1e2) / 1e6d, + ForcePerLengthUnit.MeganewtonPerMeter => (baseUnitValue) / 1e6d, + ForcePerLengthUnit.MeganewtonPerMillimeter => (baseUnitValue / 1e3) / 1e6d, + ForcePerLengthUnit.MicronewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-6d, + ForcePerLengthUnit.MicronewtonPerMeter => (baseUnitValue) / 1e-6d, + ForcePerLengthUnit.MicronewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-6d, + ForcePerLengthUnit.MillinewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-3d, + ForcePerLengthUnit.MillinewtonPerMeter => (baseUnitValue) / 1e-3d, + ForcePerLengthUnit.MillinewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-3d, + ForcePerLengthUnit.NanonewtonPerCentimeter => (baseUnitValue / 1e2) / 1e-9d, + ForcePerLengthUnit.NanonewtonPerMeter => (baseUnitValue) / 1e-9d, + ForcePerLengthUnit.NanonewtonPerMillimeter => (baseUnitValue / 1e3) / 1e-9d, + ForcePerLengthUnit.NewtonPerCentimeter => baseUnitValue / 1e2, + ForcePerLengthUnit.NewtonPerMeter => baseUnitValue, + ForcePerLengthUnit.NewtonPerMillimeter => baseUnitValue / 1e3, + ForcePerLengthUnit.PoundForcePerFoot => baseUnitValue / 14.59390292, + ForcePerLengthUnit.PoundForcePerInch => baseUnitValue / 1.75126835e2, + ForcePerLengthUnit.PoundForcePerYard => baseUnitValue / 4.864634307, + ForcePerLengthUnit.TonneForcePerCentimeter => baseUnitValue / 9.80665002864e5, + ForcePerLengthUnit.TonneForcePerMeter => baseUnitValue / 9.80665002864e3, + ForcePerLengthUnit.TonneForcePerMillimeter => baseUnitValue / 9.80665002864e6, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs index 35a1b42715..735e48489b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Frequency.g.cs @@ -217,73 +217,73 @@ public static Frequency From(double value, FrequencyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FrequencyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Frequency ToUnit(FrequencyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Frequency(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - FrequencyUnit.BeatPerMinute => _value / 60, - FrequencyUnit.BUnit => Math.Sqrt(_value * 1e3), - FrequencyUnit.CyclePerHour => _value / 3600, - FrequencyUnit.CyclePerMinute => _value / 60, - FrequencyUnit.Gigahertz => (_value) * 1e9d, - FrequencyUnit.Hertz => _value, - FrequencyUnit.Kilohertz => (_value) * 1e3d, - FrequencyUnit.Megahertz => (_value) * 1e6d, - FrequencyUnit.PerSecond => _value, - FrequencyUnit.RadianPerSecond => _value / 6.2831853072, - FrequencyUnit.Terahertz => (_value) * 1e12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(FrequencyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - FrequencyUnit.BeatPerMinute => baseUnitValue * 60, - FrequencyUnit.BUnit => baseUnitValue * baseUnitValue * 1e-3, - FrequencyUnit.CyclePerHour => baseUnitValue * 3600, - FrequencyUnit.CyclePerMinute => baseUnitValue * 60, - FrequencyUnit.Gigahertz => (baseUnitValue) / 1e9d, - FrequencyUnit.Hertz => baseUnitValue, - FrequencyUnit.Kilohertz => (baseUnitValue) / 1e3d, - FrequencyUnit.Megahertz => (baseUnitValue) / 1e6d, - FrequencyUnit.PerSecond => baseUnitValue, - FrequencyUnit.RadianPerSecond => baseUnitValue * 6.2831853072, - FrequencyUnit.Terahertz => (baseUnitValue) / 1e12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FrequencyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Frequency ToUnit(FrequencyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Frequency(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + FrequencyUnit.BeatPerMinute => _value / 60, + FrequencyUnit.BUnit => Math.Sqrt(_value * 1e3), + FrequencyUnit.CyclePerHour => _value / 3600, + FrequencyUnit.CyclePerMinute => _value / 60, + FrequencyUnit.Gigahertz => (_value) * 1e9d, + FrequencyUnit.Hertz => _value, + FrequencyUnit.Kilohertz => (_value) * 1e3d, + FrequencyUnit.Megahertz => (_value) * 1e6d, + FrequencyUnit.PerSecond => _value, + FrequencyUnit.RadianPerSecond => _value / 6.2831853072, + FrequencyUnit.Terahertz => (_value) * 1e12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(FrequencyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + FrequencyUnit.BeatPerMinute => baseUnitValue * 60, + FrequencyUnit.BUnit => baseUnitValue * baseUnitValue * 1e-3, + FrequencyUnit.CyclePerHour => baseUnitValue * 3600, + FrequencyUnit.CyclePerMinute => baseUnitValue * 60, + FrequencyUnit.Gigahertz => (baseUnitValue) / 1e9d, + FrequencyUnit.Hertz => baseUnitValue, + FrequencyUnit.Kilohertz => (baseUnitValue) / 1e3d, + FrequencyUnit.Megahertz => (baseUnitValue) / 1e6d, + FrequencyUnit.PerSecond => baseUnitValue, + FrequencyUnit.RadianPerSecond => baseUnitValue * 6.2831853072, + FrequencyUnit.Terahertz => (baseUnitValue) / 1e12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/FuelEfficiency.g.cs index 88bf83347b..e1ff33660e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -143,59 +143,59 @@ public static FuelEfficiency From(double value, FuelEfficiencyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FuelEfficiencyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new FuelEfficiency(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - FuelEfficiencyUnit.KilometerPerLiter => 100 / _value, - FuelEfficiencyUnit.LiterPer100Kilometers => _value, - FuelEfficiencyUnit.MilePerUkGallon => (100 * 4.54609188) / (1.609344 * _value), - FuelEfficiencyUnit.MilePerUsGallon => (100 * 3.785411784) / (1.609344 * _value), - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(FuelEfficiencyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - FuelEfficiencyUnit.KilometerPerLiter => 100 / baseUnitValue, - FuelEfficiencyUnit.LiterPer100Kilometers => baseUnitValue, - FuelEfficiencyUnit.MilePerUkGallon => (100 * 4.54609188) / (1.609344 * baseUnitValue), - FuelEfficiencyUnit.MilePerUsGallon => (100 * 3.785411784) / (1.609344 * baseUnitValue), - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FuelEfficiencyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new FuelEfficiency(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + FuelEfficiencyUnit.KilometerPerLiter => 100 / _value, + FuelEfficiencyUnit.LiterPer100Kilometers => _value, + FuelEfficiencyUnit.MilePerUkGallon => (100 * 4.54609188) / (1.609344 * _value), + FuelEfficiencyUnit.MilePerUsGallon => (100 * 3.785411784) / (1.609344 * _value), + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(FuelEfficiencyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + FuelEfficiencyUnit.KilometerPerLiter => 100 / baseUnitValue, + FuelEfficiencyUnit.LiterPer100Kilometers => baseUnitValue, + FuelEfficiencyUnit.MilePerUkGallon => (100 * 4.54609188) / (1.609344 * baseUnitValue), + FuelEfficiencyUnit.MilePerUsGallon => (100 * 3.785411784) / (1.609344 * baseUnitValue), + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatFlux.g.cs index 663d5c0e91..9f21f8753a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatFlux.g.cs @@ -294,87 +294,87 @@ public static HeatFlux From(double value, HeatFluxUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatFluxUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public HeatFlux ToUnit(HeatFluxUnit unit) - { - var convertedValue = GetValueAs(unit); - return new HeatFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - HeatFluxUnit.BtuPerHourSquareFoot => _value * 3.15459075, - HeatFluxUnit.BtuPerMinuteSquareFoot => _value * 1.89275445e2, - HeatFluxUnit.BtuPerSecondSquareFoot => _value * 1.13565267e4, - HeatFluxUnit.BtuPerSecondSquareInch => _value * 1.63533984e6, - HeatFluxUnit.CaloriePerSecondSquareCentimeter => _value * 4.1868e4, - HeatFluxUnit.CentiwattPerSquareMeter => (_value) * 1e-2d, - HeatFluxUnit.DeciwattPerSquareMeter => (_value) * 1e-1d, - HeatFluxUnit.KilocaloriePerHourSquareMeter => _value * 1.163, - HeatFluxUnit.KilocaloriePerSecondSquareCentimeter => (_value * 4.1868e4) * 1e3d, - HeatFluxUnit.KilowattPerSquareMeter => (_value) * 1e3d, - HeatFluxUnit.MicrowattPerSquareMeter => (_value) * 1e-6d, - HeatFluxUnit.MilliwattPerSquareMeter => (_value) * 1e-3d, - HeatFluxUnit.NanowattPerSquareMeter => (_value) * 1e-9d, - HeatFluxUnit.PoundForcePerFootSecond => _value * 1.459390293720636e1, - HeatFluxUnit.PoundPerSecondCubed => _value * 4.5359237e-1, - HeatFluxUnit.WattPerSquareFoot => _value * 1.07639e1, - HeatFluxUnit.WattPerSquareInch => _value * 1.5500031e3, - HeatFluxUnit.WattPerSquareMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(HeatFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - HeatFluxUnit.BtuPerHourSquareFoot => baseUnitValue / 3.15459075, - HeatFluxUnit.BtuPerMinuteSquareFoot => baseUnitValue / 1.89275445e2, - HeatFluxUnit.BtuPerSecondSquareFoot => baseUnitValue / 1.13565267e4, - HeatFluxUnit.BtuPerSecondSquareInch => baseUnitValue / 1.63533984e6, - HeatFluxUnit.CaloriePerSecondSquareCentimeter => baseUnitValue / 4.1868e4, - HeatFluxUnit.CentiwattPerSquareMeter => (baseUnitValue) / 1e-2d, - HeatFluxUnit.DeciwattPerSquareMeter => (baseUnitValue) / 1e-1d, - HeatFluxUnit.KilocaloriePerHourSquareMeter => baseUnitValue / 1.163, - HeatFluxUnit.KilocaloriePerSecondSquareCentimeter => (baseUnitValue / 4.1868e4) / 1e3d, - HeatFluxUnit.KilowattPerSquareMeter => (baseUnitValue) / 1e3d, - HeatFluxUnit.MicrowattPerSquareMeter => (baseUnitValue) / 1e-6d, - HeatFluxUnit.MilliwattPerSquareMeter => (baseUnitValue) / 1e-3d, - HeatFluxUnit.NanowattPerSquareMeter => (baseUnitValue) / 1e-9d, - HeatFluxUnit.PoundForcePerFootSecond => baseUnitValue / 1.459390293720636e1, - HeatFluxUnit.PoundPerSecondCubed => baseUnitValue / 4.5359237e-1, - HeatFluxUnit.WattPerSquareFoot => baseUnitValue / 1.07639e1, - HeatFluxUnit.WattPerSquareInch => baseUnitValue / 1.5500031e3, - HeatFluxUnit.WattPerSquareMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(HeatFluxUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public HeatFlux ToUnit(HeatFluxUnit unit) + { + var convertedValue = GetValueAs(unit); + return new HeatFlux(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + HeatFluxUnit.BtuPerHourSquareFoot => _value * 3.15459075, + HeatFluxUnit.BtuPerMinuteSquareFoot => _value * 1.89275445e2, + HeatFluxUnit.BtuPerSecondSquareFoot => _value * 1.13565267e4, + HeatFluxUnit.BtuPerSecondSquareInch => _value * 1.63533984e6, + HeatFluxUnit.CaloriePerSecondSquareCentimeter => _value * 4.1868e4, + HeatFluxUnit.CentiwattPerSquareMeter => (_value) * 1e-2d, + HeatFluxUnit.DeciwattPerSquareMeter => (_value) * 1e-1d, + HeatFluxUnit.KilocaloriePerHourSquareMeter => _value * 1.163, + HeatFluxUnit.KilocaloriePerSecondSquareCentimeter => (_value * 4.1868e4) * 1e3d, + HeatFluxUnit.KilowattPerSquareMeter => (_value) * 1e3d, + HeatFluxUnit.MicrowattPerSquareMeter => (_value) * 1e-6d, + HeatFluxUnit.MilliwattPerSquareMeter => (_value) * 1e-3d, + HeatFluxUnit.NanowattPerSquareMeter => (_value) * 1e-9d, + HeatFluxUnit.PoundForcePerFootSecond => _value * 1.459390293720636e1, + HeatFluxUnit.PoundPerSecondCubed => _value * 4.5359237e-1, + HeatFluxUnit.WattPerSquareFoot => _value * 1.07639e1, + HeatFluxUnit.WattPerSquareInch => _value * 1.5500031e3, + HeatFluxUnit.WattPerSquareMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(HeatFluxUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + HeatFluxUnit.BtuPerHourSquareFoot => baseUnitValue / 3.15459075, + HeatFluxUnit.BtuPerMinuteSquareFoot => baseUnitValue / 1.89275445e2, + HeatFluxUnit.BtuPerSecondSquareFoot => baseUnitValue / 1.13565267e4, + HeatFluxUnit.BtuPerSecondSquareInch => baseUnitValue / 1.63533984e6, + HeatFluxUnit.CaloriePerSecondSquareCentimeter => baseUnitValue / 4.1868e4, + HeatFluxUnit.CentiwattPerSquareMeter => (baseUnitValue) / 1e-2d, + HeatFluxUnit.DeciwattPerSquareMeter => (baseUnitValue) / 1e-1d, + HeatFluxUnit.KilocaloriePerHourSquareMeter => baseUnitValue / 1.163, + HeatFluxUnit.KilocaloriePerSecondSquareCentimeter => (baseUnitValue / 4.1868e4) / 1e3d, + HeatFluxUnit.KilowattPerSquareMeter => (baseUnitValue) / 1e3d, + HeatFluxUnit.MicrowattPerSquareMeter => (baseUnitValue) / 1e-6d, + HeatFluxUnit.MilliwattPerSquareMeter => (baseUnitValue) / 1e-3d, + HeatFluxUnit.NanowattPerSquareMeter => (baseUnitValue) / 1e-9d, + HeatFluxUnit.PoundForcePerFootSecond => baseUnitValue / 1.459390293720636e1, + HeatFluxUnit.PoundPerSecondCubed => baseUnitValue / 4.5359237e-1, + HeatFluxUnit.WattPerSquareFoot => baseUnitValue / 1.07639e1, + HeatFluxUnit.WattPerSquareInch => baseUnitValue / 1.5500031e3, + HeatFluxUnit.WattPerSquareMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index e41a4d1f9d..b658044414 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -129,57 +129,57 @@ public static HeatTransferCoefficient From(double value, HeatTransferCoefficient #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatTransferCoefficientUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) - { - var convertedValue = GetValueAs(unit); - return new HeatTransferCoefficient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit => _value * 5.6782633411134878, - HeatTransferCoefficientUnit.WattPerSquareMeterCelsius => _value, - HeatTransferCoefficientUnit.WattPerSquareMeterKelvin => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(HeatTransferCoefficientUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit => baseUnitValue / 5.6782633411134878, - HeatTransferCoefficientUnit.WattPerSquareMeterCelsius => baseUnitValue, - HeatTransferCoefficientUnit.WattPerSquareMeterKelvin => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(HeatTransferCoefficientUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) + { + var convertedValue = GetValueAs(unit); + return new HeatTransferCoefficient(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit => _value * 5.6782633411134878, + HeatTransferCoefficientUnit.WattPerSquareMeterCelsius => _value, + HeatTransferCoefficientUnit.WattPerSquareMeterKelvin => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(HeatTransferCoefficientUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit => baseUnitValue / 5.6782633411134878, + HeatTransferCoefficientUnit.WattPerSquareMeterCelsius => baseUnitValue, + HeatTransferCoefficientUnit.WattPerSquareMeterKelvin => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Illuminance.g.cs index 7cbd646bfc..2bcef415eb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Illuminance.g.cs @@ -143,59 +143,59 @@ public static Illuminance From(double value, IlluminanceUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IlluminanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Illuminance ToUnit(IlluminanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Illuminance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - IlluminanceUnit.Kilolux => (_value) * 1e3d, - IlluminanceUnit.Lux => _value, - IlluminanceUnit.Megalux => (_value) * 1e6d, - IlluminanceUnit.Millilux => (_value) * 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(IlluminanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - IlluminanceUnit.Kilolux => (baseUnitValue) / 1e3d, - IlluminanceUnit.Lux => baseUnitValue, - IlluminanceUnit.Megalux => (baseUnitValue) / 1e6d, - IlluminanceUnit.Millilux => (baseUnitValue) / 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IlluminanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Illuminance ToUnit(IlluminanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Illuminance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + IlluminanceUnit.Kilolux => (_value) * 1e3d, + IlluminanceUnit.Lux => _value, + IlluminanceUnit.Megalux => (_value) * 1e6d, + IlluminanceUnit.Millilux => (_value) * 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(IlluminanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + IlluminanceUnit.Kilolux => (baseUnitValue) / 1e3d, + IlluminanceUnit.Lux => baseUnitValue, + IlluminanceUnit.Megalux => (baseUnitValue) / 1e6d, + IlluminanceUnit.Millilux => (baseUnitValue) / 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Information.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Information.g.cs index 37a249fb11..0da45220a1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Information.g.cs @@ -382,103 +382,103 @@ public static Information From(double value, InformationUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(InformationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Information ToUnit(InformationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Information(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - InformationUnit.Bit => _value, - InformationUnit.Byte => _value * 8d, - InformationUnit.Exabit => (_value) * 1e18d, - InformationUnit.Exabyte => (_value * 8d) * 1e18d, - InformationUnit.Exbibit => (_value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - InformationUnit.Exbibyte => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - InformationUnit.Gibibit => (_value) * (1024d * 1024 * 1024), - InformationUnit.Gibibyte => (_value * 8d) * (1024d * 1024 * 1024), - InformationUnit.Gigabit => (_value) * 1e9d, - InformationUnit.Gigabyte => (_value * 8d) * 1e9d, - InformationUnit.Kibibit => (_value) * 1024d, - InformationUnit.Kibibyte => (_value * 8d) * 1024d, - InformationUnit.Kilobit => (_value) * 1e3d, - InformationUnit.Kilobyte => (_value * 8d) * 1e3d, - InformationUnit.Mebibit => (_value) * (1024d * 1024), - InformationUnit.Mebibyte => (_value * 8d) * (1024d * 1024), - InformationUnit.Megabit => (_value) * 1e6d, - InformationUnit.Megabyte => (_value * 8d) * 1e6d, - InformationUnit.Pebibit => (_value) * (1024d * 1024 * 1024 * 1024 * 1024), - InformationUnit.Pebibyte => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024), - InformationUnit.Petabit => (_value) * 1e15d, - InformationUnit.Petabyte => (_value * 8d) * 1e15d, - InformationUnit.Tebibit => (_value) * (1024d * 1024 * 1024 * 1024), - InformationUnit.Tebibyte => (_value * 8d) * (1024d * 1024 * 1024 * 1024), - InformationUnit.Terabit => (_value) * 1e12d, - InformationUnit.Terabyte => (_value * 8d) * 1e12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(InformationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - InformationUnit.Bit => baseUnitValue, - InformationUnit.Byte => baseUnitValue / 8d, - InformationUnit.Exabit => (baseUnitValue) / 1e18d, - InformationUnit.Exabyte => (baseUnitValue / 8d) / 1e18d, - InformationUnit.Exbibit => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - InformationUnit.Exbibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), - InformationUnit.Gibibit => (baseUnitValue) / (1024d * 1024 * 1024), - InformationUnit.Gibibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024), - InformationUnit.Gigabit => (baseUnitValue) / 1e9d, - InformationUnit.Gigabyte => (baseUnitValue / 8d) / 1e9d, - InformationUnit.Kibibit => (baseUnitValue) / 1024d, - InformationUnit.Kibibyte => (baseUnitValue / 8d) / 1024d, - InformationUnit.Kilobit => (baseUnitValue) / 1e3d, - InformationUnit.Kilobyte => (baseUnitValue / 8d) / 1e3d, - InformationUnit.Mebibit => (baseUnitValue) / (1024d * 1024), - InformationUnit.Mebibyte => (baseUnitValue / 8d) / (1024d * 1024), - InformationUnit.Megabit => (baseUnitValue) / 1e6d, - InformationUnit.Megabyte => (baseUnitValue / 8d) / 1e6d, - InformationUnit.Pebibit => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024), - InformationUnit.Pebibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024), - InformationUnit.Petabit => (baseUnitValue) / 1e15d, - InformationUnit.Petabyte => (baseUnitValue / 8d) / 1e15d, - InformationUnit.Tebibit => (baseUnitValue) / (1024d * 1024 * 1024 * 1024), - InformationUnit.Tebibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024), - InformationUnit.Terabit => (baseUnitValue) / 1e12d, - InformationUnit.Terabyte => (baseUnitValue / 8d) / 1e12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(InformationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Information ToUnit(InformationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Information(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + InformationUnit.Bit => _value, + InformationUnit.Byte => _value * 8d, + InformationUnit.Exabit => (_value) * 1e18d, + InformationUnit.Exabyte => (_value * 8d) * 1e18d, + InformationUnit.Exbibit => (_value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + InformationUnit.Exbibyte => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + InformationUnit.Gibibit => (_value) * (1024d * 1024 * 1024), + InformationUnit.Gibibyte => (_value * 8d) * (1024d * 1024 * 1024), + InformationUnit.Gigabit => (_value) * 1e9d, + InformationUnit.Gigabyte => (_value * 8d) * 1e9d, + InformationUnit.Kibibit => (_value) * 1024d, + InformationUnit.Kibibyte => (_value * 8d) * 1024d, + InformationUnit.Kilobit => (_value) * 1e3d, + InformationUnit.Kilobyte => (_value * 8d) * 1e3d, + InformationUnit.Mebibit => (_value) * (1024d * 1024), + InformationUnit.Mebibyte => (_value * 8d) * (1024d * 1024), + InformationUnit.Megabit => (_value) * 1e6d, + InformationUnit.Megabyte => (_value * 8d) * 1e6d, + InformationUnit.Pebibit => (_value) * (1024d * 1024 * 1024 * 1024 * 1024), + InformationUnit.Pebibyte => (_value * 8d) * (1024d * 1024 * 1024 * 1024 * 1024), + InformationUnit.Petabit => (_value) * 1e15d, + InformationUnit.Petabyte => (_value * 8d) * 1e15d, + InformationUnit.Tebibit => (_value) * (1024d * 1024 * 1024 * 1024), + InformationUnit.Tebibyte => (_value * 8d) * (1024d * 1024 * 1024 * 1024), + InformationUnit.Terabit => (_value) * 1e12d, + InformationUnit.Terabyte => (_value * 8d) * 1e12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(InformationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + InformationUnit.Bit => baseUnitValue, + InformationUnit.Byte => baseUnitValue / 8d, + InformationUnit.Exabit => (baseUnitValue) / 1e18d, + InformationUnit.Exabyte => (baseUnitValue / 8d) / 1e18d, + InformationUnit.Exbibit => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + InformationUnit.Exbibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), + InformationUnit.Gibibit => (baseUnitValue) / (1024d * 1024 * 1024), + InformationUnit.Gibibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024), + InformationUnit.Gigabit => (baseUnitValue) / 1e9d, + InformationUnit.Gigabyte => (baseUnitValue / 8d) / 1e9d, + InformationUnit.Kibibit => (baseUnitValue) / 1024d, + InformationUnit.Kibibyte => (baseUnitValue / 8d) / 1024d, + InformationUnit.Kilobit => (baseUnitValue) / 1e3d, + InformationUnit.Kilobyte => (baseUnitValue / 8d) / 1e3d, + InformationUnit.Mebibit => (baseUnitValue) / (1024d * 1024), + InformationUnit.Mebibyte => (baseUnitValue / 8d) / (1024d * 1024), + InformationUnit.Megabit => (baseUnitValue) / 1e6d, + InformationUnit.Megabyte => (baseUnitValue / 8d) / 1e6d, + InformationUnit.Pebibit => (baseUnitValue) / (1024d * 1024 * 1024 * 1024 * 1024), + InformationUnit.Pebibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024 * 1024), + InformationUnit.Petabit => (baseUnitValue) / 1e15d, + InformationUnit.Petabyte => (baseUnitValue / 8d) / 1e15d, + InformationUnit.Tebibit => (baseUnitValue) / (1024d * 1024 * 1024 * 1024), + InformationUnit.Tebibyte => (baseUnitValue / 8d) / (1024d * 1024 * 1024 * 1024), + InformationUnit.Terabit => (baseUnitValue) / 1e12d, + InformationUnit.Terabyte => (baseUnitValue / 8d) / 1e12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiance.g.cs index 2109a4f820..a9fc36b729 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiance.g.cs @@ -250,79 +250,79 @@ public static Irradiance From(double value, IrradianceUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradianceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Irradiance ToUnit(IrradianceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Irradiance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - IrradianceUnit.KilowattPerSquareCentimeter => (_value * 10000) * 1e3d, - IrradianceUnit.KilowattPerSquareMeter => (_value) * 1e3d, - IrradianceUnit.MegawattPerSquareCentimeter => (_value * 10000) * 1e6d, - IrradianceUnit.MegawattPerSquareMeter => (_value) * 1e6d, - IrradianceUnit.MicrowattPerSquareCentimeter => (_value * 10000) * 1e-6d, - IrradianceUnit.MicrowattPerSquareMeter => (_value) * 1e-6d, - IrradianceUnit.MilliwattPerSquareCentimeter => (_value * 10000) * 1e-3d, - IrradianceUnit.MilliwattPerSquareMeter => (_value) * 1e-3d, - IrradianceUnit.NanowattPerSquareCentimeter => (_value * 10000) * 1e-9d, - IrradianceUnit.NanowattPerSquareMeter => (_value) * 1e-9d, - IrradianceUnit.PicowattPerSquareCentimeter => (_value * 10000) * 1e-12d, - IrradianceUnit.PicowattPerSquareMeter => (_value) * 1e-12d, - IrradianceUnit.WattPerSquareCentimeter => _value * 10000, - IrradianceUnit.WattPerSquareMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(IrradianceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - IrradianceUnit.KilowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e3d, - IrradianceUnit.KilowattPerSquareMeter => (baseUnitValue) / 1e3d, - IrradianceUnit.MegawattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e6d, - IrradianceUnit.MegawattPerSquareMeter => (baseUnitValue) / 1e6d, - IrradianceUnit.MicrowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-6d, - IrradianceUnit.MicrowattPerSquareMeter => (baseUnitValue) / 1e-6d, - IrradianceUnit.MilliwattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-3d, - IrradianceUnit.MilliwattPerSquareMeter => (baseUnitValue) / 1e-3d, - IrradianceUnit.NanowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-9d, - IrradianceUnit.NanowattPerSquareMeter => (baseUnitValue) / 1e-9d, - IrradianceUnit.PicowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-12d, - IrradianceUnit.PicowattPerSquareMeter => (baseUnitValue) / 1e-12d, - IrradianceUnit.WattPerSquareCentimeter => baseUnitValue * 0.0001, - IrradianceUnit.WattPerSquareMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IrradianceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Irradiance ToUnit(IrradianceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Irradiance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + IrradianceUnit.KilowattPerSquareCentimeter => (_value * 10000) * 1e3d, + IrradianceUnit.KilowattPerSquareMeter => (_value) * 1e3d, + IrradianceUnit.MegawattPerSquareCentimeter => (_value * 10000) * 1e6d, + IrradianceUnit.MegawattPerSquareMeter => (_value) * 1e6d, + IrradianceUnit.MicrowattPerSquareCentimeter => (_value * 10000) * 1e-6d, + IrradianceUnit.MicrowattPerSquareMeter => (_value) * 1e-6d, + IrradianceUnit.MilliwattPerSquareCentimeter => (_value * 10000) * 1e-3d, + IrradianceUnit.MilliwattPerSquareMeter => (_value) * 1e-3d, + IrradianceUnit.NanowattPerSquareCentimeter => (_value * 10000) * 1e-9d, + IrradianceUnit.NanowattPerSquareMeter => (_value) * 1e-9d, + IrradianceUnit.PicowattPerSquareCentimeter => (_value * 10000) * 1e-12d, + IrradianceUnit.PicowattPerSquareMeter => (_value) * 1e-12d, + IrradianceUnit.WattPerSquareCentimeter => _value * 10000, + IrradianceUnit.WattPerSquareMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(IrradianceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + IrradianceUnit.KilowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e3d, + IrradianceUnit.KilowattPerSquareMeter => (baseUnitValue) / 1e3d, + IrradianceUnit.MegawattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e6d, + IrradianceUnit.MegawattPerSquareMeter => (baseUnitValue) / 1e6d, + IrradianceUnit.MicrowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-6d, + IrradianceUnit.MicrowattPerSquareMeter => (baseUnitValue) / 1e-6d, + IrradianceUnit.MilliwattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-3d, + IrradianceUnit.MilliwattPerSquareMeter => (baseUnitValue) / 1e-3d, + IrradianceUnit.NanowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-9d, + IrradianceUnit.NanowattPerSquareMeter => (baseUnitValue) / 1e-9d, + IrradianceUnit.PicowattPerSquareCentimeter => (baseUnitValue * 0.0001) / 1e-12d, + IrradianceUnit.PicowattPerSquareMeter => (baseUnitValue) / 1e-12d, + IrradianceUnit.WattPerSquareCentimeter => baseUnitValue * 0.0001, + IrradianceUnit.WattPerSquareMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiation.g.cs index 8bfc2d69de..7e3ddcd7d1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Irradiation.g.cs @@ -176,65 +176,65 @@ public static Irradiation From(double value, IrradiationUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradiationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Irradiation ToUnit(IrradiationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Irradiation(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - IrradiationUnit.JoulePerSquareCentimeter => _value * 1e4, - IrradiationUnit.JoulePerSquareMeter => _value, - IrradiationUnit.JoulePerSquareMillimeter => _value * 1e6, - IrradiationUnit.KilojoulePerSquareMeter => (_value) * 1e3d, - IrradiationUnit.KilowattHourPerSquareMeter => (_value * 3600d) * 1e3d, - IrradiationUnit.MillijoulePerSquareCentimeter => (_value * 1e4) * 1e-3d, - IrradiationUnit.WattHourPerSquareMeter => _value * 3600d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(IrradiationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - IrradiationUnit.JoulePerSquareCentimeter => baseUnitValue / 1e4, - IrradiationUnit.JoulePerSquareMeter => baseUnitValue, - IrradiationUnit.JoulePerSquareMillimeter => baseUnitValue / 1e6, - IrradiationUnit.KilojoulePerSquareMeter => (baseUnitValue) / 1e3d, - IrradiationUnit.KilowattHourPerSquareMeter => (baseUnitValue / 3600d) / 1e3d, - IrradiationUnit.MillijoulePerSquareCentimeter => (baseUnitValue / 1e4) / 1e-3d, - IrradiationUnit.WattHourPerSquareMeter => baseUnitValue / 3600d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(IrradiationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Irradiation ToUnit(IrradiationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Irradiation(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + IrradiationUnit.JoulePerSquareCentimeter => _value * 1e4, + IrradiationUnit.JoulePerSquareMeter => _value, + IrradiationUnit.JoulePerSquareMillimeter => _value * 1e6, + IrradiationUnit.KilojoulePerSquareMeter => (_value) * 1e3d, + IrradiationUnit.KilowattHourPerSquareMeter => (_value * 3600d) * 1e3d, + IrradiationUnit.MillijoulePerSquareCentimeter => (_value * 1e4) * 1e-3d, + IrradiationUnit.WattHourPerSquareMeter => _value * 3600d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(IrradiationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + IrradiationUnit.JoulePerSquareCentimeter => baseUnitValue / 1e4, + IrradiationUnit.JoulePerSquareMeter => baseUnitValue, + IrradiationUnit.JoulePerSquareMillimeter => baseUnitValue / 1e6, + IrradiationUnit.KilojoulePerSquareMeter => (baseUnitValue) / 1e3d, + IrradiationUnit.KilowattHourPerSquareMeter => (baseUnitValue / 3600d) / 1e3d, + IrradiationUnit.MillijoulePerSquareCentimeter => (baseUnitValue / 1e4) / 1e-3d, + IrradiationUnit.WattHourPerSquareMeter => baseUnitValue / 3600d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Jerk.g.cs index 7ff8f250dc..840714bf46 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Jerk.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Jerk.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// Jerk or Jolt, in physics, is the rate at which the acceleration of an object changes over time. The SI unit for jerk is the Meter per second cubed (m/s³). Jerks are vector quantities (they have magnitude and direction) and add according to the parallelogram law. + /// /// public struct Jerk { @@ -217,73 +217,73 @@ public static Jerk From(double value, JerkUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(JerkUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Jerk ToUnit(JerkUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Jerk(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - JerkUnit.CentimeterPerSecondCubed => (_value) * 1e-2d, - JerkUnit.DecimeterPerSecondCubed => (_value) * 1e-1d, - JerkUnit.FootPerSecondCubed => _value * 0.304800, - JerkUnit.InchPerSecondCubed => _value * 0.0254, - JerkUnit.KilometerPerSecondCubed => (_value) * 1e3d, - JerkUnit.MeterPerSecondCubed => _value, - JerkUnit.MicrometerPerSecondCubed => (_value) * 1e-6d, - JerkUnit.MillimeterPerSecondCubed => (_value) * 1e-3d, - JerkUnit.MillistandardGravitiesPerSecond => (_value * 9.80665) * 1e-3d, - JerkUnit.NanometerPerSecondCubed => (_value) * 1e-9d, - JerkUnit.StandardGravitiesPerSecond => _value * 9.80665, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(JerkUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - JerkUnit.CentimeterPerSecondCubed => (baseUnitValue) / 1e-2d, - JerkUnit.DecimeterPerSecondCubed => (baseUnitValue) / 1e-1d, - JerkUnit.FootPerSecondCubed => baseUnitValue / 0.304800, - JerkUnit.InchPerSecondCubed => baseUnitValue / 0.0254, - JerkUnit.KilometerPerSecondCubed => (baseUnitValue) / 1e3d, - JerkUnit.MeterPerSecondCubed => baseUnitValue, - JerkUnit.MicrometerPerSecondCubed => (baseUnitValue) / 1e-6d, - JerkUnit.MillimeterPerSecondCubed => (baseUnitValue) / 1e-3d, - JerkUnit.MillistandardGravitiesPerSecond => (baseUnitValue / 9.80665) / 1e-3d, - JerkUnit.NanometerPerSecondCubed => (baseUnitValue) / 1e-9d, - JerkUnit.StandardGravitiesPerSecond => baseUnitValue / 9.80665, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(JerkUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Jerk ToUnit(JerkUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Jerk(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + JerkUnit.CentimeterPerSecondCubed => (_value) * 1e-2d, + JerkUnit.DecimeterPerSecondCubed => (_value) * 1e-1d, + JerkUnit.FootPerSecondCubed => _value * 0.304800, + JerkUnit.InchPerSecondCubed => _value * 0.0254, + JerkUnit.KilometerPerSecondCubed => (_value) * 1e3d, + JerkUnit.MeterPerSecondCubed => _value, + JerkUnit.MicrometerPerSecondCubed => (_value) * 1e-6d, + JerkUnit.MillimeterPerSecondCubed => (_value) * 1e-3d, + JerkUnit.MillistandardGravitiesPerSecond => (_value * 9.80665) * 1e-3d, + JerkUnit.NanometerPerSecondCubed => (_value) * 1e-9d, + JerkUnit.StandardGravitiesPerSecond => _value * 9.80665, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(JerkUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + JerkUnit.CentimeterPerSecondCubed => (baseUnitValue) / 1e-2d, + JerkUnit.DecimeterPerSecondCubed => (baseUnitValue) / 1e-1d, + JerkUnit.FootPerSecondCubed => baseUnitValue / 0.304800, + JerkUnit.InchPerSecondCubed => baseUnitValue / 0.0254, + JerkUnit.KilometerPerSecondCubed => (baseUnitValue) / 1e3d, + JerkUnit.MeterPerSecondCubed => baseUnitValue, + JerkUnit.MicrometerPerSecondCubed => (baseUnitValue) / 1e-6d, + JerkUnit.MillimeterPerSecondCubed => (baseUnitValue) / 1e-3d, + JerkUnit.MillistandardGravitiesPerSecond => (baseUnitValue / 9.80665) / 1e-3d, + JerkUnit.NanometerPerSecondCubed => (baseUnitValue) / 1e-9d, + JerkUnit.StandardGravitiesPerSecond => baseUnitValue / 9.80665, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/KinematicViscosity.g.cs index f5d96aceb6..40e4491a76 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -198,69 +198,69 @@ public static KinematicViscosity From(double value, KinematicViscosityUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(KinematicViscosityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public KinematicViscosity ToUnit(KinematicViscosityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new KinematicViscosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - KinematicViscosityUnit.Centistokes => (_value / 1e4) * 1e-2d, - KinematicViscosityUnit.Decistokes => (_value / 1e4) * 1e-1d, - KinematicViscosityUnit.Kilostokes => (_value / 1e4) * 1e3d, - KinematicViscosityUnit.Microstokes => (_value / 1e4) * 1e-6d, - KinematicViscosityUnit.Millistokes => (_value / 1e4) * 1e-3d, - KinematicViscosityUnit.Nanostokes => (_value / 1e4) * 1e-9d, - KinematicViscosityUnit.SquareFootPerSecond => _value / 10.7639, - KinematicViscosityUnit.SquareMeterPerSecond => _value, - KinematicViscosityUnit.Stokes => _value / 1e4, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(KinematicViscosityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - KinematicViscosityUnit.Centistokes => (baseUnitValue * 1e4) / 1e-2d, - KinematicViscosityUnit.Decistokes => (baseUnitValue * 1e4) / 1e-1d, - KinematicViscosityUnit.Kilostokes => (baseUnitValue * 1e4) / 1e3d, - KinematicViscosityUnit.Microstokes => (baseUnitValue * 1e4) / 1e-6d, - KinematicViscosityUnit.Millistokes => (baseUnitValue * 1e4) / 1e-3d, - KinematicViscosityUnit.Nanostokes => (baseUnitValue * 1e4) / 1e-9d, - KinematicViscosityUnit.SquareFootPerSecond => baseUnitValue * 10.7639, - KinematicViscosityUnit.SquareMeterPerSecond => baseUnitValue, - KinematicViscosityUnit.Stokes => baseUnitValue * 1e4, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(KinematicViscosityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public KinematicViscosity ToUnit(KinematicViscosityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new KinematicViscosity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + KinematicViscosityUnit.Centistokes => (_value / 1e4) * 1e-2d, + KinematicViscosityUnit.Decistokes => (_value / 1e4) * 1e-1d, + KinematicViscosityUnit.Kilostokes => (_value / 1e4) * 1e3d, + KinematicViscosityUnit.Microstokes => (_value / 1e4) * 1e-6d, + KinematicViscosityUnit.Millistokes => (_value / 1e4) * 1e-3d, + KinematicViscosityUnit.Nanostokes => (_value / 1e4) * 1e-9d, + KinematicViscosityUnit.SquareFootPerSecond => _value / 10.7639, + KinematicViscosityUnit.SquareMeterPerSecond => _value, + KinematicViscosityUnit.Stokes => _value / 1e4, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(KinematicViscosityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + KinematicViscosityUnit.Centistokes => (baseUnitValue * 1e4) / 1e-2d, + KinematicViscosityUnit.Decistokes => (baseUnitValue * 1e4) / 1e-1d, + KinematicViscosityUnit.Kilostokes => (baseUnitValue * 1e4) / 1e3d, + KinematicViscosityUnit.Microstokes => (baseUnitValue * 1e4) / 1e-6d, + KinematicViscosityUnit.Millistokes => (baseUnitValue * 1e4) / 1e-3d, + KinematicViscosityUnit.Nanostokes => (baseUnitValue * 1e4) / 1e-9d, + KinematicViscosityUnit.SquareFootPerSecond => baseUnitValue * 10.7639, + KinematicViscosityUnit.SquareMeterPerSecond => baseUnitValue, + KinematicViscosityUnit.Stokes => baseUnitValue * 1e4, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LapseRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LapseRate.g.cs index 2ac4f0b16e..dc9b80b169 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LapseRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LapseRate.g.cs @@ -107,53 +107,53 @@ public static LapseRate From(double value, LapseRateUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LapseRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public LapseRate ToUnit(LapseRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new LapseRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LapseRateUnit.DegreeCelsiusPerKilometer => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LapseRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LapseRateUnit.DegreeCelsiusPerKilometer => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LapseRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public LapseRate ToUnit(LapseRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new LapseRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LapseRateUnit.DegreeCelsiusPerKilometer => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LapseRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LapseRateUnit.DegreeCelsiusPerKilometer => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Length.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Length.g.cs index 38b8737054..18bbb7eb31 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Length.g.cs @@ -492,123 +492,123 @@ public static Length From(double value, LengthUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LengthUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Length ToUnit(LengthUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Length(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LengthUnit.Angstrom => _value * 1e-10, - LengthUnit.AstronomicalUnit => _value * 1.4959787070e11, - LengthUnit.Centimeter => (_value) * 1e-2d, - LengthUnit.Chain => _value * 20.1168, - LengthUnit.DataMile => _value * 1828.8, - LengthUnit.Decameter => (_value) * 1e1d, - LengthUnit.Decimeter => (_value) * 1e-1d, - LengthUnit.DtpPica => _value / 236.220472441, - LengthUnit.DtpPoint => (_value / 72) * 2.54e-2, - LengthUnit.Fathom => _value * 1.8288, - LengthUnit.Foot => _value * 0.3048, - LengthUnit.Hand => _value * 1.016e-1, - LengthUnit.Hectometer => (_value) * 1e2d, - LengthUnit.Inch => _value * 2.54e-2, - LengthUnit.KilolightYear => (_value * 9.46073047258e15) * 1e3d, - LengthUnit.Kilometer => (_value) * 1e3d, - LengthUnit.Kiloparsec => (_value * 3.08567758128e16) * 1e3d, - LengthUnit.LightYear => _value * 9.46073047258e15, - LengthUnit.MegalightYear => (_value * 9.46073047258e15) * 1e6d, - LengthUnit.Megaparsec => (_value * 3.08567758128e16) * 1e6d, - LengthUnit.Meter => _value, - LengthUnit.Microinch => _value * 2.54e-8, - LengthUnit.Micrometer => (_value) * 1e-6d, - LengthUnit.Mil => _value * 2.54e-5, - LengthUnit.Mile => _value * 1609.34, - LengthUnit.Millimeter => (_value) * 1e-3d, - LengthUnit.Nanometer => (_value) * 1e-9d, - LengthUnit.NauticalMile => _value * 1852, - LengthUnit.Parsec => _value * 3.08567758128e16, - LengthUnit.PrinterPica => _value / 237.106301584, - LengthUnit.PrinterPoint => (_value / 72.27) * 2.54e-2, - LengthUnit.Shackle => _value * 27.432, - LengthUnit.SolarRadius => _value * 6.95510000E+08, - LengthUnit.Twip => _value / 56692.913385826, - LengthUnit.UsSurveyFoot => _value * 1200 / 3937, - LengthUnit.Yard => _value * 0.9144, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LengthUnit.Angstrom => baseUnitValue / 1e-10, - LengthUnit.AstronomicalUnit => baseUnitValue / 1.4959787070e11, - LengthUnit.Centimeter => (baseUnitValue) / 1e-2d, - LengthUnit.Chain => baseUnitValue / 20.1168, - LengthUnit.DataMile => baseUnitValue / 1828.8, - LengthUnit.Decameter => (baseUnitValue) / 1e1d, - LengthUnit.Decimeter => (baseUnitValue) / 1e-1d, - LengthUnit.DtpPica => baseUnitValue * 236.220472441, - LengthUnit.DtpPoint => (baseUnitValue / 2.54e-2) * 72, - LengthUnit.Fathom => baseUnitValue / 1.8288, - LengthUnit.Foot => baseUnitValue / 0.3048, - LengthUnit.Hand => baseUnitValue / 1.016e-1, - LengthUnit.Hectometer => (baseUnitValue) / 1e2d, - LengthUnit.Inch => baseUnitValue / 2.54e-2, - LengthUnit.KilolightYear => (baseUnitValue / 9.46073047258e15) / 1e3d, - LengthUnit.Kilometer => (baseUnitValue) / 1e3d, - LengthUnit.Kiloparsec => (baseUnitValue / 3.08567758128e16) / 1e3d, - LengthUnit.LightYear => baseUnitValue / 9.46073047258e15, - LengthUnit.MegalightYear => (baseUnitValue / 9.46073047258e15) / 1e6d, - LengthUnit.Megaparsec => (baseUnitValue / 3.08567758128e16) / 1e6d, - LengthUnit.Meter => baseUnitValue, - LengthUnit.Microinch => baseUnitValue / 2.54e-8, - LengthUnit.Micrometer => (baseUnitValue) / 1e-6d, - LengthUnit.Mil => baseUnitValue / 2.54e-5, - LengthUnit.Mile => baseUnitValue / 1609.34, - LengthUnit.Millimeter => (baseUnitValue) / 1e-3d, - LengthUnit.Nanometer => (baseUnitValue) / 1e-9d, - LengthUnit.NauticalMile => baseUnitValue / 1852, - LengthUnit.Parsec => baseUnitValue / 3.08567758128e16, - LengthUnit.PrinterPica => baseUnitValue * 237.106301584, - LengthUnit.PrinterPoint => (baseUnitValue / 2.54e-2) * 72.27, - LengthUnit.Shackle => baseUnitValue / 27.432, - LengthUnit.SolarRadius => baseUnitValue / 6.95510000E+08, - LengthUnit.Twip => baseUnitValue * 56692.913385826, - LengthUnit.UsSurveyFoot => baseUnitValue * 3937 / 1200, - LengthUnit.Yard => baseUnitValue / 0.9144, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LengthUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Length ToUnit(LengthUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Length(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LengthUnit.Angstrom => _value * 1e-10, + LengthUnit.AstronomicalUnit => _value * 1.4959787070e11, + LengthUnit.Centimeter => (_value) * 1e-2d, + LengthUnit.Chain => _value * 20.1168, + LengthUnit.DataMile => _value * 1828.8, + LengthUnit.Decameter => (_value) * 1e1d, + LengthUnit.Decimeter => (_value) * 1e-1d, + LengthUnit.DtpPica => _value / 236.220472441, + LengthUnit.DtpPoint => (_value / 72) * 2.54e-2, + LengthUnit.Fathom => _value * 1.8288, + LengthUnit.Foot => _value * 0.3048, + LengthUnit.Hand => _value * 1.016e-1, + LengthUnit.Hectometer => (_value) * 1e2d, + LengthUnit.Inch => _value * 2.54e-2, + LengthUnit.KilolightYear => (_value * 9.46073047258e15) * 1e3d, + LengthUnit.Kilometer => (_value) * 1e3d, + LengthUnit.Kiloparsec => (_value * 3.08567758128e16) * 1e3d, + LengthUnit.LightYear => _value * 9.46073047258e15, + LengthUnit.MegalightYear => (_value * 9.46073047258e15) * 1e6d, + LengthUnit.Megaparsec => (_value * 3.08567758128e16) * 1e6d, + LengthUnit.Meter => _value, + LengthUnit.Microinch => _value * 2.54e-8, + LengthUnit.Micrometer => (_value) * 1e-6d, + LengthUnit.Mil => _value * 2.54e-5, + LengthUnit.Mile => _value * 1609.34, + LengthUnit.Millimeter => (_value) * 1e-3d, + LengthUnit.Nanometer => (_value) * 1e-9d, + LengthUnit.NauticalMile => _value * 1852, + LengthUnit.Parsec => _value * 3.08567758128e16, + LengthUnit.PrinterPica => _value / 237.106301584, + LengthUnit.PrinterPoint => (_value / 72.27) * 2.54e-2, + LengthUnit.Shackle => _value * 27.432, + LengthUnit.SolarRadius => _value * 6.95510000E+08, + LengthUnit.Twip => _value / 56692.913385826, + LengthUnit.UsSurveyFoot => _value * 1200 / 3937, + LengthUnit.Yard => _value * 0.9144, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LengthUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LengthUnit.Angstrom => baseUnitValue / 1e-10, + LengthUnit.AstronomicalUnit => baseUnitValue / 1.4959787070e11, + LengthUnit.Centimeter => (baseUnitValue) / 1e-2d, + LengthUnit.Chain => baseUnitValue / 20.1168, + LengthUnit.DataMile => baseUnitValue / 1828.8, + LengthUnit.Decameter => (baseUnitValue) / 1e1d, + LengthUnit.Decimeter => (baseUnitValue) / 1e-1d, + LengthUnit.DtpPica => baseUnitValue * 236.220472441, + LengthUnit.DtpPoint => (baseUnitValue / 2.54e-2) * 72, + LengthUnit.Fathom => baseUnitValue / 1.8288, + LengthUnit.Foot => baseUnitValue / 0.3048, + LengthUnit.Hand => baseUnitValue / 1.016e-1, + LengthUnit.Hectometer => (baseUnitValue) / 1e2d, + LengthUnit.Inch => baseUnitValue / 2.54e-2, + LengthUnit.KilolightYear => (baseUnitValue / 9.46073047258e15) / 1e3d, + LengthUnit.Kilometer => (baseUnitValue) / 1e3d, + LengthUnit.Kiloparsec => (baseUnitValue / 3.08567758128e16) / 1e3d, + LengthUnit.LightYear => baseUnitValue / 9.46073047258e15, + LengthUnit.MegalightYear => (baseUnitValue / 9.46073047258e15) / 1e6d, + LengthUnit.Megaparsec => (baseUnitValue / 3.08567758128e16) / 1e6d, + LengthUnit.Meter => baseUnitValue, + LengthUnit.Microinch => baseUnitValue / 2.54e-8, + LengthUnit.Micrometer => (baseUnitValue) / 1e-6d, + LengthUnit.Mil => baseUnitValue / 2.54e-5, + LengthUnit.Mile => baseUnitValue / 1609.34, + LengthUnit.Millimeter => (baseUnitValue) / 1e-3d, + LengthUnit.Nanometer => (baseUnitValue) / 1e-9d, + LengthUnit.NauticalMile => baseUnitValue / 1852, + LengthUnit.Parsec => baseUnitValue / 3.08567758128e16, + LengthUnit.PrinterPica => baseUnitValue * 237.106301584, + LengthUnit.PrinterPoint => (baseUnitValue / 2.54e-2) * 72.27, + LengthUnit.Shackle => baseUnitValue / 27.432, + LengthUnit.SolarRadius => baseUnitValue / 6.95510000E+08, + LengthUnit.Twip => baseUnitValue * 56692.913385826, + LengthUnit.UsSurveyFoot => baseUnitValue * 3937 / 1200, + LengthUnit.Yard => baseUnitValue / 0.9144, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Level.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Level.g.cs index e47b3cc027..7712cb841c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Level.g.cs @@ -118,55 +118,55 @@ public static Level From(double value, LevelUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LevelUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Level ToUnit(LevelUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Level(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LevelUnit.Decibel => _value, - LevelUnit.Neper => (1 / 0.115129254) * _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LevelUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LevelUnit.Decibel => baseUnitValue, - LevelUnit.Neper => 0.115129254 * baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LevelUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Level ToUnit(LevelUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Level(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LevelUnit.Decibel => _value, + LevelUnit.Neper => (1 / 0.115129254) * _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LevelUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LevelUnit.Decibel => baseUnitValue, + LevelUnit.Neper => 0.115129254 * baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearDensity.g.cs index a6bf44f82b..8bdd837334 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearDensity.g.cs @@ -253,79 +253,79 @@ public static LinearDensity From(double value, LinearDensityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public LinearDensity ToUnit(LinearDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new LinearDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LinearDensityUnit.GramPerCentimeter => _value * 1e-1, - LinearDensityUnit.GramPerMeter => _value * 1e-3, - LinearDensityUnit.GramPerMillimeter => _value, - LinearDensityUnit.KilogramPerCentimeter => (_value * 1e-1) * 1e3d, - LinearDensityUnit.KilogramPerMeter => (_value * 1e-3) * 1e3d, - LinearDensityUnit.KilogramPerMillimeter => (_value) * 1e3d, - LinearDensityUnit.MicrogramPerCentimeter => (_value * 1e-1) * 1e-6d, - LinearDensityUnit.MicrogramPerMeter => (_value * 1e-3) * 1e-6d, - LinearDensityUnit.MicrogramPerMillimeter => (_value) * 1e-6d, - LinearDensityUnit.MilligramPerCentimeter => (_value * 1e-1) * 1e-3d, - LinearDensityUnit.MilligramPerMeter => (_value * 1e-3) * 1e-3d, - LinearDensityUnit.MilligramPerMillimeter => (_value) * 1e-3d, - LinearDensityUnit.PoundPerFoot => _value * 1.48816394, - LinearDensityUnit.PoundPerInch => _value / 5.5997415e-2, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LinearDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LinearDensityUnit.GramPerCentimeter => baseUnitValue / 1e-1, - LinearDensityUnit.GramPerMeter => baseUnitValue / 1e-3, - LinearDensityUnit.GramPerMillimeter => baseUnitValue, - LinearDensityUnit.KilogramPerCentimeter => (baseUnitValue / 1e-1) / 1e3d, - LinearDensityUnit.KilogramPerMeter => (baseUnitValue / 1e-3) / 1e3d, - LinearDensityUnit.KilogramPerMillimeter => (baseUnitValue) / 1e3d, - LinearDensityUnit.MicrogramPerCentimeter => (baseUnitValue / 1e-1) / 1e-6d, - LinearDensityUnit.MicrogramPerMeter => (baseUnitValue / 1e-3) / 1e-6d, - LinearDensityUnit.MicrogramPerMillimeter => (baseUnitValue) / 1e-6d, - LinearDensityUnit.MilligramPerCentimeter => (baseUnitValue / 1e-1) / 1e-3d, - LinearDensityUnit.MilligramPerMeter => (baseUnitValue / 1e-3) / 1e-3d, - LinearDensityUnit.MilligramPerMillimeter => (baseUnitValue) / 1e-3d, - LinearDensityUnit.PoundPerFoot => baseUnitValue / 1.48816394, - LinearDensityUnit.PoundPerInch => baseUnitValue * 5.5997415e-2, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LinearDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public LinearDensity ToUnit(LinearDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new LinearDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LinearDensityUnit.GramPerCentimeter => _value * 1e-1, + LinearDensityUnit.GramPerMeter => _value * 1e-3, + LinearDensityUnit.GramPerMillimeter => _value, + LinearDensityUnit.KilogramPerCentimeter => (_value * 1e-1) * 1e3d, + LinearDensityUnit.KilogramPerMeter => (_value * 1e-3) * 1e3d, + LinearDensityUnit.KilogramPerMillimeter => (_value) * 1e3d, + LinearDensityUnit.MicrogramPerCentimeter => (_value * 1e-1) * 1e-6d, + LinearDensityUnit.MicrogramPerMeter => (_value * 1e-3) * 1e-6d, + LinearDensityUnit.MicrogramPerMillimeter => (_value) * 1e-6d, + LinearDensityUnit.MilligramPerCentimeter => (_value * 1e-1) * 1e-3d, + LinearDensityUnit.MilligramPerMeter => (_value * 1e-3) * 1e-3d, + LinearDensityUnit.MilligramPerMillimeter => (_value) * 1e-3d, + LinearDensityUnit.PoundPerFoot => _value * 1.48816394, + LinearDensityUnit.PoundPerInch => _value / 5.5997415e-2, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LinearDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LinearDensityUnit.GramPerCentimeter => baseUnitValue / 1e-1, + LinearDensityUnit.GramPerMeter => baseUnitValue / 1e-3, + LinearDensityUnit.GramPerMillimeter => baseUnitValue, + LinearDensityUnit.KilogramPerCentimeter => (baseUnitValue / 1e-1) / 1e3d, + LinearDensityUnit.KilogramPerMeter => (baseUnitValue / 1e-3) / 1e3d, + LinearDensityUnit.KilogramPerMillimeter => (baseUnitValue) / 1e3d, + LinearDensityUnit.MicrogramPerCentimeter => (baseUnitValue / 1e-1) / 1e-6d, + LinearDensityUnit.MicrogramPerMeter => (baseUnitValue / 1e-3) / 1e-6d, + LinearDensityUnit.MicrogramPerMillimeter => (baseUnitValue) / 1e-6d, + LinearDensityUnit.MilligramPerCentimeter => (baseUnitValue / 1e-1) / 1e-3d, + LinearDensityUnit.MilligramPerMeter => (baseUnitValue / 1e-3) / 1e-3d, + LinearDensityUnit.MilligramPerMillimeter => (baseUnitValue) / 1e-3d, + LinearDensityUnit.PoundPerFoot => baseUnitValue / 1.48816394, + LinearDensityUnit.PoundPerInch => baseUnitValue * 5.5997415e-2, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearPowerDensity.g.cs index 71ba8e36c7..d86cf7fcc2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -374,101 +374,101 @@ public static LinearPowerDensity From(double value, LinearPowerDensityUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearPowerDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new LinearPowerDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LinearPowerDensityUnit.GigawattPerCentimeter => (_value * 1e2) * 1e9d, - LinearPowerDensityUnit.GigawattPerFoot => (_value * 3.280839895) * 1e9d, - LinearPowerDensityUnit.GigawattPerInch => (_value * 39.37007874) * 1e9d, - LinearPowerDensityUnit.GigawattPerMeter => (_value) * 1e9d, - LinearPowerDensityUnit.GigawattPerMillimeter => (_value * 1e3) * 1e9d, - LinearPowerDensityUnit.KilowattPerCentimeter => (_value * 1e2) * 1e3d, - LinearPowerDensityUnit.KilowattPerFoot => (_value * 3.280839895) * 1e3d, - LinearPowerDensityUnit.KilowattPerInch => (_value * 39.37007874) * 1e3d, - LinearPowerDensityUnit.KilowattPerMeter => (_value) * 1e3d, - LinearPowerDensityUnit.KilowattPerMillimeter => (_value * 1e3) * 1e3d, - LinearPowerDensityUnit.MegawattPerCentimeter => (_value * 1e2) * 1e6d, - LinearPowerDensityUnit.MegawattPerFoot => (_value * 3.280839895) * 1e6d, - LinearPowerDensityUnit.MegawattPerInch => (_value * 39.37007874) * 1e6d, - LinearPowerDensityUnit.MegawattPerMeter => (_value) * 1e6d, - LinearPowerDensityUnit.MegawattPerMillimeter => (_value * 1e3) * 1e6d, - LinearPowerDensityUnit.MilliwattPerCentimeter => (_value * 1e2) * 1e-3d, - LinearPowerDensityUnit.MilliwattPerFoot => (_value * 3.280839895) * 1e-3d, - LinearPowerDensityUnit.MilliwattPerInch => (_value * 39.37007874) * 1e-3d, - LinearPowerDensityUnit.MilliwattPerMeter => (_value) * 1e-3d, - LinearPowerDensityUnit.MilliwattPerMillimeter => (_value * 1e3) * 1e-3d, - LinearPowerDensityUnit.WattPerCentimeter => _value * 1e2, - LinearPowerDensityUnit.WattPerFoot => _value * 3.280839895, - LinearPowerDensityUnit.WattPerInch => _value * 39.37007874, - LinearPowerDensityUnit.WattPerMeter => _value, - LinearPowerDensityUnit.WattPerMillimeter => _value * 1e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LinearPowerDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LinearPowerDensityUnit.GigawattPerCentimeter => (baseUnitValue / 1e2) / 1e9d, - LinearPowerDensityUnit.GigawattPerFoot => (baseUnitValue / 3.280839895) / 1e9d, - LinearPowerDensityUnit.GigawattPerInch => (baseUnitValue / 39.37007874) / 1e9d, - LinearPowerDensityUnit.GigawattPerMeter => (baseUnitValue) / 1e9d, - LinearPowerDensityUnit.GigawattPerMillimeter => (baseUnitValue / 1e3) / 1e9d, - LinearPowerDensityUnit.KilowattPerCentimeter => (baseUnitValue / 1e2) / 1e3d, - LinearPowerDensityUnit.KilowattPerFoot => (baseUnitValue / 3.280839895) / 1e3d, - LinearPowerDensityUnit.KilowattPerInch => (baseUnitValue / 39.37007874) / 1e3d, - LinearPowerDensityUnit.KilowattPerMeter => (baseUnitValue) / 1e3d, - LinearPowerDensityUnit.KilowattPerMillimeter => (baseUnitValue / 1e3) / 1e3d, - LinearPowerDensityUnit.MegawattPerCentimeter => (baseUnitValue / 1e2) / 1e6d, - LinearPowerDensityUnit.MegawattPerFoot => (baseUnitValue / 3.280839895) / 1e6d, - LinearPowerDensityUnit.MegawattPerInch => (baseUnitValue / 39.37007874) / 1e6d, - LinearPowerDensityUnit.MegawattPerMeter => (baseUnitValue) / 1e6d, - LinearPowerDensityUnit.MegawattPerMillimeter => (baseUnitValue / 1e3) / 1e6d, - LinearPowerDensityUnit.MilliwattPerCentimeter => (baseUnitValue / 1e2) / 1e-3d, - LinearPowerDensityUnit.MilliwattPerFoot => (baseUnitValue / 3.280839895) / 1e-3d, - LinearPowerDensityUnit.MilliwattPerInch => (baseUnitValue / 39.37007874) / 1e-3d, - LinearPowerDensityUnit.MilliwattPerMeter => (baseUnitValue) / 1e-3d, - LinearPowerDensityUnit.MilliwattPerMillimeter => (baseUnitValue / 1e3) / 1e-3d, - LinearPowerDensityUnit.WattPerCentimeter => baseUnitValue / 1e2, - LinearPowerDensityUnit.WattPerFoot => baseUnitValue / 3.280839895, - LinearPowerDensityUnit.WattPerInch => baseUnitValue / 39.37007874, - LinearPowerDensityUnit.WattPerMeter => baseUnitValue, - LinearPowerDensityUnit.WattPerMillimeter => baseUnitValue / 1e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LinearPowerDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new LinearPowerDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LinearPowerDensityUnit.GigawattPerCentimeter => (_value * 1e2) * 1e9d, + LinearPowerDensityUnit.GigawattPerFoot => (_value * 3.280839895) * 1e9d, + LinearPowerDensityUnit.GigawattPerInch => (_value * 39.37007874) * 1e9d, + LinearPowerDensityUnit.GigawattPerMeter => (_value) * 1e9d, + LinearPowerDensityUnit.GigawattPerMillimeter => (_value * 1e3) * 1e9d, + LinearPowerDensityUnit.KilowattPerCentimeter => (_value * 1e2) * 1e3d, + LinearPowerDensityUnit.KilowattPerFoot => (_value * 3.280839895) * 1e3d, + LinearPowerDensityUnit.KilowattPerInch => (_value * 39.37007874) * 1e3d, + LinearPowerDensityUnit.KilowattPerMeter => (_value) * 1e3d, + LinearPowerDensityUnit.KilowattPerMillimeter => (_value * 1e3) * 1e3d, + LinearPowerDensityUnit.MegawattPerCentimeter => (_value * 1e2) * 1e6d, + LinearPowerDensityUnit.MegawattPerFoot => (_value * 3.280839895) * 1e6d, + LinearPowerDensityUnit.MegawattPerInch => (_value * 39.37007874) * 1e6d, + LinearPowerDensityUnit.MegawattPerMeter => (_value) * 1e6d, + LinearPowerDensityUnit.MegawattPerMillimeter => (_value * 1e3) * 1e6d, + LinearPowerDensityUnit.MilliwattPerCentimeter => (_value * 1e2) * 1e-3d, + LinearPowerDensityUnit.MilliwattPerFoot => (_value * 3.280839895) * 1e-3d, + LinearPowerDensityUnit.MilliwattPerInch => (_value * 39.37007874) * 1e-3d, + LinearPowerDensityUnit.MilliwattPerMeter => (_value) * 1e-3d, + LinearPowerDensityUnit.MilliwattPerMillimeter => (_value * 1e3) * 1e-3d, + LinearPowerDensityUnit.WattPerCentimeter => _value * 1e2, + LinearPowerDensityUnit.WattPerFoot => _value * 3.280839895, + LinearPowerDensityUnit.WattPerInch => _value * 39.37007874, + LinearPowerDensityUnit.WattPerMeter => _value, + LinearPowerDensityUnit.WattPerMillimeter => _value * 1e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LinearPowerDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LinearPowerDensityUnit.GigawattPerCentimeter => (baseUnitValue / 1e2) / 1e9d, + LinearPowerDensityUnit.GigawattPerFoot => (baseUnitValue / 3.280839895) / 1e9d, + LinearPowerDensityUnit.GigawattPerInch => (baseUnitValue / 39.37007874) / 1e9d, + LinearPowerDensityUnit.GigawattPerMeter => (baseUnitValue) / 1e9d, + LinearPowerDensityUnit.GigawattPerMillimeter => (baseUnitValue / 1e3) / 1e9d, + LinearPowerDensityUnit.KilowattPerCentimeter => (baseUnitValue / 1e2) / 1e3d, + LinearPowerDensityUnit.KilowattPerFoot => (baseUnitValue / 3.280839895) / 1e3d, + LinearPowerDensityUnit.KilowattPerInch => (baseUnitValue / 39.37007874) / 1e3d, + LinearPowerDensityUnit.KilowattPerMeter => (baseUnitValue) / 1e3d, + LinearPowerDensityUnit.KilowattPerMillimeter => (baseUnitValue / 1e3) / 1e3d, + LinearPowerDensityUnit.MegawattPerCentimeter => (baseUnitValue / 1e2) / 1e6d, + LinearPowerDensityUnit.MegawattPerFoot => (baseUnitValue / 3.280839895) / 1e6d, + LinearPowerDensityUnit.MegawattPerInch => (baseUnitValue / 39.37007874) / 1e6d, + LinearPowerDensityUnit.MegawattPerMeter => (baseUnitValue) / 1e6d, + LinearPowerDensityUnit.MegawattPerMillimeter => (baseUnitValue / 1e3) / 1e6d, + LinearPowerDensityUnit.MilliwattPerCentimeter => (baseUnitValue / 1e2) / 1e-3d, + LinearPowerDensityUnit.MilliwattPerFoot => (baseUnitValue / 3.280839895) / 1e-3d, + LinearPowerDensityUnit.MilliwattPerInch => (baseUnitValue / 39.37007874) / 1e-3d, + LinearPowerDensityUnit.MilliwattPerMeter => (baseUnitValue) / 1e-3d, + LinearPowerDensityUnit.MilliwattPerMillimeter => (baseUnitValue / 1e3) / 1e-3d, + LinearPowerDensityUnit.WattPerCentimeter => baseUnitValue / 1e2, + LinearPowerDensityUnit.WattPerFoot => baseUnitValue / 3.280839895, + LinearPowerDensityUnit.WattPerInch => baseUnitValue / 39.37007874, + LinearPowerDensityUnit.WattPerMeter => baseUnitValue, + LinearPowerDensityUnit.WattPerMillimeter => baseUnitValue / 1e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminance.g.cs index 7437e39b8b..c89d2c5378 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminance.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// Luminance is a photometric measure of the luminous intensity per unit area of light travelling in a given direction. + /// /// /// /// https://en.wikipedia.org/wiki/Luminance @@ -209,71 +209,71 @@ public static Luminance From(double value, LuminanceUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Luminance ToUnit(LuminanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Luminance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LuminanceUnit.CandelaPerSquareFoot => _value* 1.07639e1, - LuminanceUnit.CandelaPerSquareInch => _value* 1.5500031e3, - LuminanceUnit.CandelaPerSquareMeter => _value, - LuminanceUnit.CenticandelaPerSquareMeter => (_value) * 1e-2d, - LuminanceUnit.DecicandelaPerSquareMeter => (_value) * 1e-1d, - LuminanceUnit.KilocandelaPerSquareMeter => (_value) * 1e3d, - LuminanceUnit.MicrocandelaPerSquareMeter => (_value) * 1e-6d, - LuminanceUnit.MillicandelaPerSquareMeter => (_value) * 1e-3d, - LuminanceUnit.NanocandelaPerSquareMeter => (_value) * 1e-9d, - LuminanceUnit.Nit => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LuminanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LuminanceUnit.CandelaPerSquareFoot => baseUnitValue/ 1.07639e1, - LuminanceUnit.CandelaPerSquareInch => baseUnitValue/ 1.5500031e3, - LuminanceUnit.CandelaPerSquareMeter => baseUnitValue, - LuminanceUnit.CenticandelaPerSquareMeter => (baseUnitValue) / 1e-2d, - LuminanceUnit.DecicandelaPerSquareMeter => (baseUnitValue) / 1e-1d, - LuminanceUnit.KilocandelaPerSquareMeter => (baseUnitValue) / 1e3d, - LuminanceUnit.MicrocandelaPerSquareMeter => (baseUnitValue) / 1e-6d, - LuminanceUnit.MillicandelaPerSquareMeter => (baseUnitValue) / 1e-3d, - LuminanceUnit.NanocandelaPerSquareMeter => (baseUnitValue) / 1e-9d, - LuminanceUnit.Nit => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Luminance ToUnit(LuminanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Luminance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LuminanceUnit.CandelaPerSquareFoot => _value* 1.07639e1, + LuminanceUnit.CandelaPerSquareInch => _value* 1.5500031e3, + LuminanceUnit.CandelaPerSquareMeter => _value, + LuminanceUnit.CenticandelaPerSquareMeter => (_value) * 1e-2d, + LuminanceUnit.DecicandelaPerSquareMeter => (_value) * 1e-1d, + LuminanceUnit.KilocandelaPerSquareMeter => (_value) * 1e3d, + LuminanceUnit.MicrocandelaPerSquareMeter => (_value) * 1e-6d, + LuminanceUnit.MillicandelaPerSquareMeter => (_value) * 1e-3d, + LuminanceUnit.NanocandelaPerSquareMeter => (_value) * 1e-9d, + LuminanceUnit.Nit => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LuminanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LuminanceUnit.CandelaPerSquareFoot => baseUnitValue/ 1.07639e1, + LuminanceUnit.CandelaPerSquareInch => baseUnitValue/ 1.5500031e3, + LuminanceUnit.CandelaPerSquareMeter => baseUnitValue, + LuminanceUnit.CenticandelaPerSquareMeter => (baseUnitValue) / 1e-2d, + LuminanceUnit.DecicandelaPerSquareMeter => (baseUnitValue) / 1e-1d, + LuminanceUnit.KilocandelaPerSquareMeter => (baseUnitValue) / 1e3d, + LuminanceUnit.MicrocandelaPerSquareMeter => (baseUnitValue) / 1e-6d, + LuminanceUnit.MillicandelaPerSquareMeter => (baseUnitValue) / 1e-3d, + LuminanceUnit.NanocandelaPerSquareMeter => (baseUnitValue) / 1e-9d, + LuminanceUnit.Nit => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminosity.g.cs index 5e7cd41d70..7e3f1fd836 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Luminosity.g.cs @@ -253,79 +253,79 @@ public static Luminosity From(double value, LuminosityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminosityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Luminosity ToUnit(LuminosityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Luminosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LuminosityUnit.Decawatt => (_value) * 1e1d, - LuminosityUnit.Deciwatt => (_value) * 1e-1d, - LuminosityUnit.Femtowatt => (_value) * 1e-15d, - LuminosityUnit.Gigawatt => (_value) * 1e9d, - LuminosityUnit.Kilowatt => (_value) * 1e3d, - LuminosityUnit.Megawatt => (_value) * 1e6d, - LuminosityUnit.Microwatt => (_value) * 1e-6d, - LuminosityUnit.Milliwatt => (_value) * 1e-3d, - LuminosityUnit.Nanowatt => (_value) * 1e-9d, - LuminosityUnit.Petawatt => (_value) * 1e15d, - LuminosityUnit.Picowatt => (_value) * 1e-12d, - LuminosityUnit.SolarLuminosity => _value * 3.846e26, - LuminosityUnit.Terawatt => (_value) * 1e12d, - LuminosityUnit.Watt => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LuminosityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LuminosityUnit.Decawatt => (baseUnitValue) / 1e1d, - LuminosityUnit.Deciwatt => (baseUnitValue) / 1e-1d, - LuminosityUnit.Femtowatt => (baseUnitValue) / 1e-15d, - LuminosityUnit.Gigawatt => (baseUnitValue) / 1e9d, - LuminosityUnit.Kilowatt => (baseUnitValue) / 1e3d, - LuminosityUnit.Megawatt => (baseUnitValue) / 1e6d, - LuminosityUnit.Microwatt => (baseUnitValue) / 1e-6d, - LuminosityUnit.Milliwatt => (baseUnitValue) / 1e-3d, - LuminosityUnit.Nanowatt => (baseUnitValue) / 1e-9d, - LuminosityUnit.Petawatt => (baseUnitValue) / 1e15d, - LuminosityUnit.Picowatt => (baseUnitValue) / 1e-12d, - LuminosityUnit.SolarLuminosity => baseUnitValue / 3.846e26, - LuminosityUnit.Terawatt => (baseUnitValue) / 1e12d, - LuminosityUnit.Watt => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminosityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Luminosity ToUnit(LuminosityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Luminosity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LuminosityUnit.Decawatt => (_value) * 1e1d, + LuminosityUnit.Deciwatt => (_value) * 1e-1d, + LuminosityUnit.Femtowatt => (_value) * 1e-15d, + LuminosityUnit.Gigawatt => (_value) * 1e9d, + LuminosityUnit.Kilowatt => (_value) * 1e3d, + LuminosityUnit.Megawatt => (_value) * 1e6d, + LuminosityUnit.Microwatt => (_value) * 1e-6d, + LuminosityUnit.Milliwatt => (_value) * 1e-3d, + LuminosityUnit.Nanowatt => (_value) * 1e-9d, + LuminosityUnit.Petawatt => (_value) * 1e15d, + LuminosityUnit.Picowatt => (_value) * 1e-12d, + LuminosityUnit.SolarLuminosity => _value * 3.846e26, + LuminosityUnit.Terawatt => (_value) * 1e12d, + LuminosityUnit.Watt => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LuminosityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LuminosityUnit.Decawatt => (baseUnitValue) / 1e1d, + LuminosityUnit.Deciwatt => (baseUnitValue) / 1e-1d, + LuminosityUnit.Femtowatt => (baseUnitValue) / 1e-15d, + LuminosityUnit.Gigawatt => (baseUnitValue) / 1e9d, + LuminosityUnit.Kilowatt => (baseUnitValue) / 1e3d, + LuminosityUnit.Megawatt => (baseUnitValue) / 1e6d, + LuminosityUnit.Microwatt => (baseUnitValue) / 1e-6d, + LuminosityUnit.Milliwatt => (baseUnitValue) / 1e-3d, + LuminosityUnit.Nanowatt => (baseUnitValue) / 1e-9d, + LuminosityUnit.Petawatt => (baseUnitValue) / 1e15d, + LuminosityUnit.Picowatt => (baseUnitValue) / 1e-12d, + LuminosityUnit.SolarLuminosity => baseUnitValue / 3.846e26, + LuminosityUnit.Terawatt => (baseUnitValue) / 1e12d, + LuminosityUnit.Watt => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousFlux.g.cs index 470fbee1c7..f7fa10211c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -110,53 +110,53 @@ public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousFluxUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public LuminousFlux ToUnit(LuminousFluxUnit unit) - { - var convertedValue = GetValueAs(unit); - return new LuminousFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LuminousFluxUnit.Lumen => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LuminousFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LuminousFluxUnit.Lumen => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminousFluxUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public LuminousFlux ToUnit(LuminousFluxUnit unit) + { + var convertedValue = GetValueAs(unit); + return new LuminousFlux(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LuminousFluxUnit.Lumen => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LuminousFluxUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LuminousFluxUnit.Lumen => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousIntensity.g.cs index 2be645d6b4..5af7491ee3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -110,53 +110,53 @@ public static LuminousIntensity From(double value, LuminousIntensityUnit fromUni #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousIntensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public LuminousIntensity ToUnit(LuminousIntensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new LuminousIntensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - LuminousIntensityUnit.Candela => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(LuminousIntensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - LuminousIntensityUnit.Candela => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(LuminousIntensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public LuminousIntensity ToUnit(LuminousIntensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new LuminousIntensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + LuminousIntensityUnit.Candela => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(LuminousIntensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + LuminousIntensityUnit.Candela => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticField.g.cs index 0230715ca2..99ce45dc2a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticField.g.cs @@ -165,63 +165,63 @@ public static MagneticField From(double value, MagneticFieldUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFieldUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MagneticField ToUnit(MagneticFieldUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MagneticField(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MagneticFieldUnit.Gauss => _value / 1e4, - MagneticFieldUnit.Microtesla => (_value) * 1e-6d, - MagneticFieldUnit.Milligauss => (_value / 1e4) * 1e-3d, - MagneticFieldUnit.Millitesla => (_value) * 1e-3d, - MagneticFieldUnit.Nanotesla => (_value) * 1e-9d, - MagneticFieldUnit.Tesla => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MagneticFieldUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MagneticFieldUnit.Gauss => baseUnitValue * 1e4, - MagneticFieldUnit.Microtesla => (baseUnitValue) / 1e-6d, - MagneticFieldUnit.Milligauss => (baseUnitValue * 1e4) / 1e-3d, - MagneticFieldUnit.Millitesla => (baseUnitValue) / 1e-3d, - MagneticFieldUnit.Nanotesla => (baseUnitValue) / 1e-9d, - MagneticFieldUnit.Tesla => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagneticFieldUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MagneticField ToUnit(MagneticFieldUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MagneticField(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MagneticFieldUnit.Gauss => _value / 1e4, + MagneticFieldUnit.Microtesla => (_value) * 1e-6d, + MagneticFieldUnit.Milligauss => (_value / 1e4) * 1e-3d, + MagneticFieldUnit.Millitesla => (_value) * 1e-3d, + MagneticFieldUnit.Nanotesla => (_value) * 1e-9d, + MagneticFieldUnit.Tesla => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MagneticFieldUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MagneticFieldUnit.Gauss => baseUnitValue * 1e4, + MagneticFieldUnit.Microtesla => (baseUnitValue) / 1e-6d, + MagneticFieldUnit.Milligauss => (baseUnitValue * 1e4) / 1e-3d, + MagneticFieldUnit.Millitesla => (baseUnitValue) / 1e-3d, + MagneticFieldUnit.Nanotesla => (baseUnitValue) / 1e-9d, + MagneticFieldUnit.Tesla => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticFlux.g.cs index 9d1468bb80..263427152b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -110,53 +110,53 @@ public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFluxUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MagneticFlux ToUnit(MagneticFluxUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MagneticFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MagneticFluxUnit.Weber => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MagneticFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MagneticFluxUnit.Weber => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagneticFluxUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MagneticFlux ToUnit(MagneticFluxUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MagneticFlux(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MagneticFluxUnit.Weber => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MagneticFluxUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MagneticFluxUnit.Weber => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Magnetization.g.cs index 70687aa20c..04bf29ac19 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Magnetization.g.cs @@ -110,53 +110,53 @@ public static Magnetization From(double value, MagnetizationUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagnetizationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Magnetization ToUnit(MagnetizationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Magnetization(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MagnetizationUnit.AmperePerMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MagnetizationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MagnetizationUnit.AmperePerMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MagnetizationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Magnetization ToUnit(MagnetizationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Magnetization(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MagnetizationUnit.AmperePerMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MagnetizationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MagnetizationUnit.AmperePerMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Mass.g.cs index 32538f80d3..8e0499dd28 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Mass.g.cs @@ -371,101 +371,101 @@ public static Mass From(double value, MassUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Mass ToUnit(MassUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Mass(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MassUnit.Centigram => (_value / 1e3) * 1e-2d, - MassUnit.Decagram => (_value / 1e3) * 1e1d, - MassUnit.Decigram => (_value / 1e3) * 1e-1d, - MassUnit.EarthMass => _value * 5.9722E+24, - MassUnit.Grain => _value / 15432.358352941431, - MassUnit.Gram => _value / 1e3, - MassUnit.Hectogram => (_value / 1e3) * 1e2d, - MassUnit.Kilogram => (_value / 1e3) * 1e3d, - MassUnit.Kilopound => (_value * 0.45359237) * 1e3d, - MassUnit.Kilotonne => (_value * 1e3) * 1e3d, - MassUnit.LongHundredweight => _value / 0.01968413055222121, - MassUnit.LongTon => _value * 1.0160469088e3, - MassUnit.Megapound => (_value * 0.45359237) * 1e6d, - MassUnit.Megatonne => (_value * 1e3) * 1e6d, - MassUnit.Microgram => (_value / 1e3) * 1e-6d, - MassUnit.Milligram => (_value / 1e3) * 1e-3d, - MassUnit.Nanogram => (_value / 1e3) * 1e-9d, - MassUnit.Ounce => _value / 35.2739619, - MassUnit.Pound => _value * 0.45359237, - MassUnit.ShortHundredweight => _value / 0.022046226218487758, - MassUnit.ShortTon => _value * 9.0718474e2, - MassUnit.Slug => _value / 6.852176556196105e-2, - MassUnit.SolarMass => _value * 1.98947e30, - MassUnit.Stone => _value / 0.1574731728702698, - MassUnit.Tonne => _value * 1e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MassUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MassUnit.Centigram => (baseUnitValue * 1e3) / 1e-2d, - MassUnit.Decagram => (baseUnitValue * 1e3) / 1e1d, - MassUnit.Decigram => (baseUnitValue * 1e3) / 1e-1d, - MassUnit.EarthMass => baseUnitValue / 5.9722E+24, - MassUnit.Grain => baseUnitValue * 15432.358352941431, - MassUnit.Gram => baseUnitValue * 1e3, - MassUnit.Hectogram => (baseUnitValue * 1e3) / 1e2d, - MassUnit.Kilogram => (baseUnitValue * 1e3) / 1e3d, - MassUnit.Kilopound => (baseUnitValue / 0.45359237) / 1e3d, - MassUnit.Kilotonne => (baseUnitValue / 1e3) / 1e3d, - MassUnit.LongHundredweight => baseUnitValue * 0.01968413055222121, - MassUnit.LongTon => baseUnitValue / 1.0160469088e3, - MassUnit.Megapound => (baseUnitValue / 0.45359237) / 1e6d, - MassUnit.Megatonne => (baseUnitValue / 1e3) / 1e6d, - MassUnit.Microgram => (baseUnitValue * 1e3) / 1e-6d, - MassUnit.Milligram => (baseUnitValue * 1e3) / 1e-3d, - MassUnit.Nanogram => (baseUnitValue * 1e3) / 1e-9d, - MassUnit.Ounce => baseUnitValue * 35.2739619, - MassUnit.Pound => baseUnitValue / 0.45359237, - MassUnit.ShortHundredweight => baseUnitValue * 0.022046226218487758, - MassUnit.ShortTon => baseUnitValue / 9.0718474e2, - MassUnit.Slug => baseUnitValue * 6.852176556196105e-2, - MassUnit.SolarMass => baseUnitValue / 1.98947e30, - MassUnit.Stone => baseUnitValue * 0.1574731728702698, - MassUnit.Tonne => baseUnitValue / 1e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Mass ToUnit(MassUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Mass(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MassUnit.Centigram => (_value / 1e3) * 1e-2d, + MassUnit.Decagram => (_value / 1e3) * 1e1d, + MassUnit.Decigram => (_value / 1e3) * 1e-1d, + MassUnit.EarthMass => _value * 5.9722E+24, + MassUnit.Grain => _value / 15432.358352941431, + MassUnit.Gram => _value / 1e3, + MassUnit.Hectogram => (_value / 1e3) * 1e2d, + MassUnit.Kilogram => (_value / 1e3) * 1e3d, + MassUnit.Kilopound => (_value * 0.45359237) * 1e3d, + MassUnit.Kilotonne => (_value * 1e3) * 1e3d, + MassUnit.LongHundredweight => _value / 0.01968413055222121, + MassUnit.LongTon => _value * 1.0160469088e3, + MassUnit.Megapound => (_value * 0.45359237) * 1e6d, + MassUnit.Megatonne => (_value * 1e3) * 1e6d, + MassUnit.Microgram => (_value / 1e3) * 1e-6d, + MassUnit.Milligram => (_value / 1e3) * 1e-3d, + MassUnit.Nanogram => (_value / 1e3) * 1e-9d, + MassUnit.Ounce => _value / 35.2739619, + MassUnit.Pound => _value * 0.45359237, + MassUnit.ShortHundredweight => _value / 0.022046226218487758, + MassUnit.ShortTon => _value * 9.0718474e2, + MassUnit.Slug => _value / 6.852176556196105e-2, + MassUnit.SolarMass => _value * 1.98947e30, + MassUnit.Stone => _value / 0.1574731728702698, + MassUnit.Tonne => _value * 1e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MassUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MassUnit.Centigram => (baseUnitValue * 1e3) / 1e-2d, + MassUnit.Decagram => (baseUnitValue * 1e3) / 1e1d, + MassUnit.Decigram => (baseUnitValue * 1e3) / 1e-1d, + MassUnit.EarthMass => baseUnitValue / 5.9722E+24, + MassUnit.Grain => baseUnitValue * 15432.358352941431, + MassUnit.Gram => baseUnitValue * 1e3, + MassUnit.Hectogram => (baseUnitValue * 1e3) / 1e2d, + MassUnit.Kilogram => (baseUnitValue * 1e3) / 1e3d, + MassUnit.Kilopound => (baseUnitValue / 0.45359237) / 1e3d, + MassUnit.Kilotonne => (baseUnitValue / 1e3) / 1e3d, + MassUnit.LongHundredweight => baseUnitValue * 0.01968413055222121, + MassUnit.LongTon => baseUnitValue / 1.0160469088e3, + MassUnit.Megapound => (baseUnitValue / 0.45359237) / 1e6d, + MassUnit.Megatonne => (baseUnitValue / 1e3) / 1e6d, + MassUnit.Microgram => (baseUnitValue * 1e3) / 1e-6d, + MassUnit.Milligram => (baseUnitValue * 1e3) / 1e-3d, + MassUnit.Nanogram => (baseUnitValue * 1e3) / 1e-9d, + MassUnit.Ounce => baseUnitValue * 35.2739619, + MassUnit.Pound => baseUnitValue / 0.45359237, + MassUnit.ShortHundredweight => baseUnitValue * 0.022046226218487758, + MassUnit.ShortTon => baseUnitValue / 9.0718474e2, + MassUnit.Slug => baseUnitValue * 6.852176556196105e-2, + MassUnit.SolarMass => baseUnitValue / 1.98947e30, + MassUnit.Stone => baseUnitValue * 0.1574731728702698, + MassUnit.Tonne => baseUnitValue / 1e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassConcentration.g.cs index ad200501a8..d79c00788b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassConcentration.g.cs @@ -638,149 +638,149 @@ public static MassConcentration From(double value, MassConcentrationUnit fromUni #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassConcentrationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MassConcentration ToUnit(MassConcentrationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MassConcentration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MassConcentrationUnit.CentigramPerDeciliter => (_value / 1e-1) * 1e-2d, - MassConcentrationUnit.CentigramPerLiter => (_value) * 1e-2d, - MassConcentrationUnit.CentigramPerMicroliter => (_value / 1e-6) * 1e-2d, - MassConcentrationUnit.CentigramPerMilliliter => (_value / 1e-3) * 1e-2d, - MassConcentrationUnit.DecigramPerDeciliter => (_value / 1e-1) * 1e-1d, - MassConcentrationUnit.DecigramPerLiter => (_value) * 1e-1d, - MassConcentrationUnit.DecigramPerMicroliter => (_value / 1e-6) * 1e-1d, - MassConcentrationUnit.DecigramPerMilliliter => (_value / 1e-3) * 1e-1d, - MassConcentrationUnit.GramPerCubicCentimeter => _value / 1e-3, - MassConcentrationUnit.GramPerCubicMeter => _value / 1e3, - MassConcentrationUnit.GramPerCubicMillimeter => _value / 1e-6, - MassConcentrationUnit.GramPerDeciliter => _value / 1e-1, - MassConcentrationUnit.GramPerLiter => _value, - MassConcentrationUnit.GramPerMicroliter => _value / 1e-6, - MassConcentrationUnit.GramPerMilliliter => _value / 1e-3, - MassConcentrationUnit.KilogramPerCubicCentimeter => (_value / 1e-3) * 1e3d, - MassConcentrationUnit.KilogramPerCubicMeter => (_value / 1e3) * 1e3d, - MassConcentrationUnit.KilogramPerCubicMillimeter => (_value / 1e-6) * 1e3d, - MassConcentrationUnit.KilogramPerLiter => (_value) * 1e3d, - MassConcentrationUnit.KilopoundPerCubicFoot => (_value / 0.062427961) * 1e3d, - MassConcentrationUnit.KilopoundPerCubicInch => (_value / 3.6127298147753e-5) * 1e3d, - MassConcentrationUnit.MicrogramPerCubicMeter => (_value / 1e3) * 1e-6d, - MassConcentrationUnit.MicrogramPerDeciliter => (_value / 1e-1) * 1e-6d, - MassConcentrationUnit.MicrogramPerLiter => (_value) * 1e-6d, - MassConcentrationUnit.MicrogramPerMicroliter => (_value / 1e-6) * 1e-6d, - MassConcentrationUnit.MicrogramPerMilliliter => (_value / 1e-3) * 1e-6d, - MassConcentrationUnit.MilligramPerCubicMeter => (_value / 1e3) * 1e-3d, - MassConcentrationUnit.MilligramPerDeciliter => (_value / 1e-1) * 1e-3d, - MassConcentrationUnit.MilligramPerLiter => (_value) * 1e-3d, - MassConcentrationUnit.MilligramPerMicroliter => (_value / 1e-6) * 1e-3d, - MassConcentrationUnit.MilligramPerMilliliter => (_value / 1e-3) * 1e-3d, - MassConcentrationUnit.NanogramPerDeciliter => (_value / 1e-1) * 1e-9d, - MassConcentrationUnit.NanogramPerLiter => (_value) * 1e-9d, - MassConcentrationUnit.NanogramPerMicroliter => (_value / 1e-6) * 1e-9d, - MassConcentrationUnit.NanogramPerMilliliter => (_value / 1e-3) * 1e-9d, - MassConcentrationUnit.OuncePerImperialGallon => _value / 0.1603586720609, - MassConcentrationUnit.OuncePerUSGallon => _value / 0.1335264711843, - MassConcentrationUnit.PicogramPerDeciliter => (_value / 1e-1) * 1e-12d, - MassConcentrationUnit.PicogramPerLiter => (_value) * 1e-12d, - MassConcentrationUnit.PicogramPerMicroliter => (_value / 1e-6) * 1e-12d, - MassConcentrationUnit.PicogramPerMilliliter => (_value / 1e-3) * 1e-12d, - MassConcentrationUnit.PoundPerCubicFoot => _value / 0.062427961, - MassConcentrationUnit.PoundPerCubicInch => _value / 3.6127298147753e-5, - MassConcentrationUnit.PoundPerImperialGallon => _value * 9.9776398e1, - MassConcentrationUnit.PoundPerUSGallon => _value * 1.19826427e2, - MassConcentrationUnit.SlugPerCubicFoot => _value * 515.378818, - MassConcentrationUnit.TonnePerCubicCentimeter => _value / 1e-9, - MassConcentrationUnit.TonnePerCubicMeter => _value / 0.001, - MassConcentrationUnit.TonnePerCubicMillimeter => _value / 1e-12, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MassConcentrationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MassConcentrationUnit.CentigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-2d, - MassConcentrationUnit.CentigramPerLiter => (baseUnitValue) / 1e-2d, - MassConcentrationUnit.CentigramPerMicroliter => (baseUnitValue * 1e-6) / 1e-2d, - MassConcentrationUnit.CentigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-2d, - MassConcentrationUnit.DecigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-1d, - MassConcentrationUnit.DecigramPerLiter => (baseUnitValue) / 1e-1d, - MassConcentrationUnit.DecigramPerMicroliter => (baseUnitValue * 1e-6) / 1e-1d, - MassConcentrationUnit.DecigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-1d, - MassConcentrationUnit.GramPerCubicCentimeter => baseUnitValue * 1e-3, - MassConcentrationUnit.GramPerCubicMeter => baseUnitValue * 1e3, - MassConcentrationUnit.GramPerCubicMillimeter => baseUnitValue * 1e-6, - MassConcentrationUnit.GramPerDeciliter => baseUnitValue * 1e-1, - MassConcentrationUnit.GramPerLiter => baseUnitValue, - MassConcentrationUnit.GramPerMicroliter => baseUnitValue * 1e-6, - MassConcentrationUnit.GramPerMilliliter => baseUnitValue * 1e-3, - MassConcentrationUnit.KilogramPerCubicCentimeter => (baseUnitValue * 1e-3) / 1e3d, - MassConcentrationUnit.KilogramPerCubicMeter => (baseUnitValue * 1e3) / 1e3d, - MassConcentrationUnit.KilogramPerCubicMillimeter => (baseUnitValue * 1e-6) / 1e3d, - MassConcentrationUnit.KilogramPerLiter => (baseUnitValue) / 1e3d, - MassConcentrationUnit.KilopoundPerCubicFoot => (baseUnitValue * 0.062427961) / 1e3d, - MassConcentrationUnit.KilopoundPerCubicInch => (baseUnitValue * 3.6127298147753e-5) / 1e3d, - MassConcentrationUnit.MicrogramPerCubicMeter => (baseUnitValue * 1e3) / 1e-6d, - MassConcentrationUnit.MicrogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-6d, - MassConcentrationUnit.MicrogramPerLiter => (baseUnitValue) / 1e-6d, - MassConcentrationUnit.MicrogramPerMicroliter => (baseUnitValue * 1e-6) / 1e-6d, - MassConcentrationUnit.MicrogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-6d, - MassConcentrationUnit.MilligramPerCubicMeter => (baseUnitValue * 1e3) / 1e-3d, - MassConcentrationUnit.MilligramPerDeciliter => (baseUnitValue * 1e-1) / 1e-3d, - MassConcentrationUnit.MilligramPerLiter => (baseUnitValue) / 1e-3d, - MassConcentrationUnit.MilligramPerMicroliter => (baseUnitValue * 1e-6) / 1e-3d, - MassConcentrationUnit.MilligramPerMilliliter => (baseUnitValue * 1e-3) / 1e-3d, - MassConcentrationUnit.NanogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-9d, - MassConcentrationUnit.NanogramPerLiter => (baseUnitValue) / 1e-9d, - MassConcentrationUnit.NanogramPerMicroliter => (baseUnitValue * 1e-6) / 1e-9d, - MassConcentrationUnit.NanogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-9d, - MassConcentrationUnit.OuncePerImperialGallon => baseUnitValue * 0.1603586720609, - MassConcentrationUnit.OuncePerUSGallon => baseUnitValue * 0.1335264711843, - MassConcentrationUnit.PicogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-12d, - MassConcentrationUnit.PicogramPerLiter => (baseUnitValue) / 1e-12d, - MassConcentrationUnit.PicogramPerMicroliter => (baseUnitValue * 1e-6) / 1e-12d, - MassConcentrationUnit.PicogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-12d, - MassConcentrationUnit.PoundPerCubicFoot => baseUnitValue * 0.062427961, - MassConcentrationUnit.PoundPerCubicInch => baseUnitValue * 3.6127298147753e-5, - MassConcentrationUnit.PoundPerImperialGallon => baseUnitValue / 9.9776398e1, - MassConcentrationUnit.PoundPerUSGallon => baseUnitValue / 1.19826427e2, - MassConcentrationUnit.SlugPerCubicFoot => baseUnitValue * 0.00194032033, - MassConcentrationUnit.TonnePerCubicCentimeter => baseUnitValue * 1e-9, - MassConcentrationUnit.TonnePerCubicMeter => baseUnitValue * 0.001, - MassConcentrationUnit.TonnePerCubicMillimeter => baseUnitValue * 1e-12, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassConcentrationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MassConcentration ToUnit(MassConcentrationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MassConcentration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MassConcentrationUnit.CentigramPerDeciliter => (_value / 1e-1) * 1e-2d, + MassConcentrationUnit.CentigramPerLiter => (_value) * 1e-2d, + MassConcentrationUnit.CentigramPerMicroliter => (_value / 1e-6) * 1e-2d, + MassConcentrationUnit.CentigramPerMilliliter => (_value / 1e-3) * 1e-2d, + MassConcentrationUnit.DecigramPerDeciliter => (_value / 1e-1) * 1e-1d, + MassConcentrationUnit.DecigramPerLiter => (_value) * 1e-1d, + MassConcentrationUnit.DecigramPerMicroliter => (_value / 1e-6) * 1e-1d, + MassConcentrationUnit.DecigramPerMilliliter => (_value / 1e-3) * 1e-1d, + MassConcentrationUnit.GramPerCubicCentimeter => _value / 1e-3, + MassConcentrationUnit.GramPerCubicMeter => _value / 1e3, + MassConcentrationUnit.GramPerCubicMillimeter => _value / 1e-6, + MassConcentrationUnit.GramPerDeciliter => _value / 1e-1, + MassConcentrationUnit.GramPerLiter => _value, + MassConcentrationUnit.GramPerMicroliter => _value / 1e-6, + MassConcentrationUnit.GramPerMilliliter => _value / 1e-3, + MassConcentrationUnit.KilogramPerCubicCentimeter => (_value / 1e-3) * 1e3d, + MassConcentrationUnit.KilogramPerCubicMeter => (_value / 1e3) * 1e3d, + MassConcentrationUnit.KilogramPerCubicMillimeter => (_value / 1e-6) * 1e3d, + MassConcentrationUnit.KilogramPerLiter => (_value) * 1e3d, + MassConcentrationUnit.KilopoundPerCubicFoot => (_value / 0.062427961) * 1e3d, + MassConcentrationUnit.KilopoundPerCubicInch => (_value / 3.6127298147753e-5) * 1e3d, + MassConcentrationUnit.MicrogramPerCubicMeter => (_value / 1e3) * 1e-6d, + MassConcentrationUnit.MicrogramPerDeciliter => (_value / 1e-1) * 1e-6d, + MassConcentrationUnit.MicrogramPerLiter => (_value) * 1e-6d, + MassConcentrationUnit.MicrogramPerMicroliter => (_value / 1e-6) * 1e-6d, + MassConcentrationUnit.MicrogramPerMilliliter => (_value / 1e-3) * 1e-6d, + MassConcentrationUnit.MilligramPerCubicMeter => (_value / 1e3) * 1e-3d, + MassConcentrationUnit.MilligramPerDeciliter => (_value / 1e-1) * 1e-3d, + MassConcentrationUnit.MilligramPerLiter => (_value) * 1e-3d, + MassConcentrationUnit.MilligramPerMicroliter => (_value / 1e-6) * 1e-3d, + MassConcentrationUnit.MilligramPerMilliliter => (_value / 1e-3) * 1e-3d, + MassConcentrationUnit.NanogramPerDeciliter => (_value / 1e-1) * 1e-9d, + MassConcentrationUnit.NanogramPerLiter => (_value) * 1e-9d, + MassConcentrationUnit.NanogramPerMicroliter => (_value / 1e-6) * 1e-9d, + MassConcentrationUnit.NanogramPerMilliliter => (_value / 1e-3) * 1e-9d, + MassConcentrationUnit.OuncePerImperialGallon => _value / 0.1603586720609, + MassConcentrationUnit.OuncePerUSGallon => _value / 0.1335264711843, + MassConcentrationUnit.PicogramPerDeciliter => (_value / 1e-1) * 1e-12d, + MassConcentrationUnit.PicogramPerLiter => (_value) * 1e-12d, + MassConcentrationUnit.PicogramPerMicroliter => (_value / 1e-6) * 1e-12d, + MassConcentrationUnit.PicogramPerMilliliter => (_value / 1e-3) * 1e-12d, + MassConcentrationUnit.PoundPerCubicFoot => _value / 0.062427961, + MassConcentrationUnit.PoundPerCubicInch => _value / 3.6127298147753e-5, + MassConcentrationUnit.PoundPerImperialGallon => _value * 9.9776398e1, + MassConcentrationUnit.PoundPerUSGallon => _value * 1.19826427e2, + MassConcentrationUnit.SlugPerCubicFoot => _value * 515.378818, + MassConcentrationUnit.TonnePerCubicCentimeter => _value / 1e-9, + MassConcentrationUnit.TonnePerCubicMeter => _value / 0.001, + MassConcentrationUnit.TonnePerCubicMillimeter => _value / 1e-12, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MassConcentrationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MassConcentrationUnit.CentigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-2d, + MassConcentrationUnit.CentigramPerLiter => (baseUnitValue) / 1e-2d, + MassConcentrationUnit.CentigramPerMicroliter => (baseUnitValue * 1e-6) / 1e-2d, + MassConcentrationUnit.CentigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-2d, + MassConcentrationUnit.DecigramPerDeciliter => (baseUnitValue * 1e-1) / 1e-1d, + MassConcentrationUnit.DecigramPerLiter => (baseUnitValue) / 1e-1d, + MassConcentrationUnit.DecigramPerMicroliter => (baseUnitValue * 1e-6) / 1e-1d, + MassConcentrationUnit.DecigramPerMilliliter => (baseUnitValue * 1e-3) / 1e-1d, + MassConcentrationUnit.GramPerCubicCentimeter => baseUnitValue * 1e-3, + MassConcentrationUnit.GramPerCubicMeter => baseUnitValue * 1e3, + MassConcentrationUnit.GramPerCubicMillimeter => baseUnitValue * 1e-6, + MassConcentrationUnit.GramPerDeciliter => baseUnitValue * 1e-1, + MassConcentrationUnit.GramPerLiter => baseUnitValue, + MassConcentrationUnit.GramPerMicroliter => baseUnitValue * 1e-6, + MassConcentrationUnit.GramPerMilliliter => baseUnitValue * 1e-3, + MassConcentrationUnit.KilogramPerCubicCentimeter => (baseUnitValue * 1e-3) / 1e3d, + MassConcentrationUnit.KilogramPerCubicMeter => (baseUnitValue * 1e3) / 1e3d, + MassConcentrationUnit.KilogramPerCubicMillimeter => (baseUnitValue * 1e-6) / 1e3d, + MassConcentrationUnit.KilogramPerLiter => (baseUnitValue) / 1e3d, + MassConcentrationUnit.KilopoundPerCubicFoot => (baseUnitValue * 0.062427961) / 1e3d, + MassConcentrationUnit.KilopoundPerCubicInch => (baseUnitValue * 3.6127298147753e-5) / 1e3d, + MassConcentrationUnit.MicrogramPerCubicMeter => (baseUnitValue * 1e3) / 1e-6d, + MassConcentrationUnit.MicrogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-6d, + MassConcentrationUnit.MicrogramPerLiter => (baseUnitValue) / 1e-6d, + MassConcentrationUnit.MicrogramPerMicroliter => (baseUnitValue * 1e-6) / 1e-6d, + MassConcentrationUnit.MicrogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-6d, + MassConcentrationUnit.MilligramPerCubicMeter => (baseUnitValue * 1e3) / 1e-3d, + MassConcentrationUnit.MilligramPerDeciliter => (baseUnitValue * 1e-1) / 1e-3d, + MassConcentrationUnit.MilligramPerLiter => (baseUnitValue) / 1e-3d, + MassConcentrationUnit.MilligramPerMicroliter => (baseUnitValue * 1e-6) / 1e-3d, + MassConcentrationUnit.MilligramPerMilliliter => (baseUnitValue * 1e-3) / 1e-3d, + MassConcentrationUnit.NanogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-9d, + MassConcentrationUnit.NanogramPerLiter => (baseUnitValue) / 1e-9d, + MassConcentrationUnit.NanogramPerMicroliter => (baseUnitValue * 1e-6) / 1e-9d, + MassConcentrationUnit.NanogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-9d, + MassConcentrationUnit.OuncePerImperialGallon => baseUnitValue * 0.1603586720609, + MassConcentrationUnit.OuncePerUSGallon => baseUnitValue * 0.1335264711843, + MassConcentrationUnit.PicogramPerDeciliter => (baseUnitValue * 1e-1) / 1e-12d, + MassConcentrationUnit.PicogramPerLiter => (baseUnitValue) / 1e-12d, + MassConcentrationUnit.PicogramPerMicroliter => (baseUnitValue * 1e-6) / 1e-12d, + MassConcentrationUnit.PicogramPerMilliliter => (baseUnitValue * 1e-3) / 1e-12d, + MassConcentrationUnit.PoundPerCubicFoot => baseUnitValue * 0.062427961, + MassConcentrationUnit.PoundPerCubicInch => baseUnitValue * 3.6127298147753e-5, + MassConcentrationUnit.PoundPerImperialGallon => baseUnitValue / 9.9776398e1, + MassConcentrationUnit.PoundPerUSGallon => baseUnitValue / 1.19826427e2, + MassConcentrationUnit.SlugPerCubicFoot => baseUnitValue * 0.00194032033, + MassConcentrationUnit.TonnePerCubicCentimeter => baseUnitValue * 1e-9, + MassConcentrationUnit.TonnePerCubicMeter => baseUnitValue * 0.001, + MassConcentrationUnit.TonnePerCubicMillimeter => baseUnitValue * 1e-12, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlow.g.cs index 1d9b9bb6da..fc9a9ec75b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlow.g.cs @@ -459,117 +459,117 @@ public static MassFlow From(double value, MassFlowUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFlowUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MassFlow ToUnit(MassFlowUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MassFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MassFlowUnit.CentigramPerDay => (_value / 86400) * 1e-2d, - MassFlowUnit.CentigramPerSecond => (_value) * 1e-2d, - MassFlowUnit.DecagramPerDay => (_value / 86400) * 1e1d, - MassFlowUnit.DecagramPerSecond => (_value) * 1e1d, - MassFlowUnit.DecigramPerDay => (_value / 86400) * 1e-1d, - MassFlowUnit.DecigramPerSecond => (_value) * 1e-1d, - MassFlowUnit.GramPerDay => _value / 86400, - MassFlowUnit.GramPerHour => _value / 3600, - MassFlowUnit.GramPerSecond => _value, - MassFlowUnit.HectogramPerDay => (_value / 86400) * 1e2d, - MassFlowUnit.HectogramPerSecond => (_value) * 1e2d, - MassFlowUnit.KilogramPerDay => (_value / 86400) * 1e3d, - MassFlowUnit.KilogramPerHour => _value / 3.6, - MassFlowUnit.KilogramPerMinute => _value / 0.06, - MassFlowUnit.KilogramPerSecond => (_value) * 1e3d, - MassFlowUnit.MegagramPerDay => (_value / 86400) * 1e6d, - MassFlowUnit.MegapoundPerDay => (_value / 190.47936) * 1e6d, - MassFlowUnit.MegapoundPerHour => (_value / 7.93664) * 1e6d, - MassFlowUnit.MegapoundPerMinute => (_value / 0.132277) * 1e6d, - MassFlowUnit.MegapoundPerSecond => (_value * 453.59237) * 1e6d, - MassFlowUnit.MicrogramPerDay => (_value / 86400) * 1e-6d, - MassFlowUnit.MicrogramPerSecond => (_value) * 1e-6d, - MassFlowUnit.MilligramPerDay => (_value / 86400) * 1e-3d, - MassFlowUnit.MilligramPerSecond => (_value) * 1e-3d, - MassFlowUnit.NanogramPerDay => (_value / 86400) * 1e-9d, - MassFlowUnit.NanogramPerSecond => (_value) * 1e-9d, - MassFlowUnit.PoundPerDay => _value / 190.47936, - MassFlowUnit.PoundPerHour => _value / 7.93664, - MassFlowUnit.PoundPerMinute => _value / 0.132277, - MassFlowUnit.PoundPerSecond => _value * 453.59237, - MassFlowUnit.ShortTonPerHour => _value * 251.9957611, - MassFlowUnit.TonnePerDay => _value / 0.0864000, - MassFlowUnit.TonnePerHour => 1000 * _value / 3.6, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MassFlowUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MassFlowUnit.CentigramPerDay => (baseUnitValue * 86400) / 1e-2d, - MassFlowUnit.CentigramPerSecond => (baseUnitValue) / 1e-2d, - MassFlowUnit.DecagramPerDay => (baseUnitValue * 86400) / 1e1d, - MassFlowUnit.DecagramPerSecond => (baseUnitValue) / 1e1d, - MassFlowUnit.DecigramPerDay => (baseUnitValue * 86400) / 1e-1d, - MassFlowUnit.DecigramPerSecond => (baseUnitValue) / 1e-1d, - MassFlowUnit.GramPerDay => baseUnitValue * 86400, - MassFlowUnit.GramPerHour => baseUnitValue * 3600, - MassFlowUnit.GramPerSecond => baseUnitValue, - MassFlowUnit.HectogramPerDay => (baseUnitValue * 86400) / 1e2d, - MassFlowUnit.HectogramPerSecond => (baseUnitValue) / 1e2d, - MassFlowUnit.KilogramPerDay => (baseUnitValue * 86400) / 1e3d, - MassFlowUnit.KilogramPerHour => baseUnitValue * 3.6, - MassFlowUnit.KilogramPerMinute => baseUnitValue * 0.06, - MassFlowUnit.KilogramPerSecond => (baseUnitValue) / 1e3d, - MassFlowUnit.MegagramPerDay => (baseUnitValue * 86400) / 1e6d, - MassFlowUnit.MegapoundPerDay => (baseUnitValue * 190.47936) / 1e6d, - MassFlowUnit.MegapoundPerHour => (baseUnitValue * 7.93664) / 1e6d, - MassFlowUnit.MegapoundPerMinute => (baseUnitValue * 0.132277) / 1e6d, - MassFlowUnit.MegapoundPerSecond => (baseUnitValue / 453.59237) / 1e6d, - MassFlowUnit.MicrogramPerDay => (baseUnitValue * 86400) / 1e-6d, - MassFlowUnit.MicrogramPerSecond => (baseUnitValue) / 1e-6d, - MassFlowUnit.MilligramPerDay => (baseUnitValue * 86400) / 1e-3d, - MassFlowUnit.MilligramPerSecond => (baseUnitValue) / 1e-3d, - MassFlowUnit.NanogramPerDay => (baseUnitValue * 86400) / 1e-9d, - MassFlowUnit.NanogramPerSecond => (baseUnitValue) / 1e-9d, - MassFlowUnit.PoundPerDay => baseUnitValue * 190.47936, - MassFlowUnit.PoundPerHour => baseUnitValue * 7.93664, - MassFlowUnit.PoundPerMinute => baseUnitValue * 0.132277, - MassFlowUnit.PoundPerSecond => baseUnitValue / 453.59237, - MassFlowUnit.ShortTonPerHour => baseUnitValue / 251.9957611, - MassFlowUnit.TonnePerDay => baseUnitValue * 0.0864000, - MassFlowUnit.TonnePerHour => baseUnitValue * 3.6 / 1000, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFlowUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MassFlow ToUnit(MassFlowUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MassFlow(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MassFlowUnit.CentigramPerDay => (_value / 86400) * 1e-2d, + MassFlowUnit.CentigramPerSecond => (_value) * 1e-2d, + MassFlowUnit.DecagramPerDay => (_value / 86400) * 1e1d, + MassFlowUnit.DecagramPerSecond => (_value) * 1e1d, + MassFlowUnit.DecigramPerDay => (_value / 86400) * 1e-1d, + MassFlowUnit.DecigramPerSecond => (_value) * 1e-1d, + MassFlowUnit.GramPerDay => _value / 86400, + MassFlowUnit.GramPerHour => _value / 3600, + MassFlowUnit.GramPerSecond => _value, + MassFlowUnit.HectogramPerDay => (_value / 86400) * 1e2d, + MassFlowUnit.HectogramPerSecond => (_value) * 1e2d, + MassFlowUnit.KilogramPerDay => (_value / 86400) * 1e3d, + MassFlowUnit.KilogramPerHour => _value / 3.6, + MassFlowUnit.KilogramPerMinute => _value / 0.06, + MassFlowUnit.KilogramPerSecond => (_value) * 1e3d, + MassFlowUnit.MegagramPerDay => (_value / 86400) * 1e6d, + MassFlowUnit.MegapoundPerDay => (_value / 190.47936) * 1e6d, + MassFlowUnit.MegapoundPerHour => (_value / 7.93664) * 1e6d, + MassFlowUnit.MegapoundPerMinute => (_value / 0.132277) * 1e6d, + MassFlowUnit.MegapoundPerSecond => (_value * 453.59237) * 1e6d, + MassFlowUnit.MicrogramPerDay => (_value / 86400) * 1e-6d, + MassFlowUnit.MicrogramPerSecond => (_value) * 1e-6d, + MassFlowUnit.MilligramPerDay => (_value / 86400) * 1e-3d, + MassFlowUnit.MilligramPerSecond => (_value) * 1e-3d, + MassFlowUnit.NanogramPerDay => (_value / 86400) * 1e-9d, + MassFlowUnit.NanogramPerSecond => (_value) * 1e-9d, + MassFlowUnit.PoundPerDay => _value / 190.47936, + MassFlowUnit.PoundPerHour => _value / 7.93664, + MassFlowUnit.PoundPerMinute => _value / 0.132277, + MassFlowUnit.PoundPerSecond => _value * 453.59237, + MassFlowUnit.ShortTonPerHour => _value * 251.9957611, + MassFlowUnit.TonnePerDay => _value / 0.0864000, + MassFlowUnit.TonnePerHour => 1000 * _value / 3.6, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MassFlowUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MassFlowUnit.CentigramPerDay => (baseUnitValue * 86400) / 1e-2d, + MassFlowUnit.CentigramPerSecond => (baseUnitValue) / 1e-2d, + MassFlowUnit.DecagramPerDay => (baseUnitValue * 86400) / 1e1d, + MassFlowUnit.DecagramPerSecond => (baseUnitValue) / 1e1d, + MassFlowUnit.DecigramPerDay => (baseUnitValue * 86400) / 1e-1d, + MassFlowUnit.DecigramPerSecond => (baseUnitValue) / 1e-1d, + MassFlowUnit.GramPerDay => baseUnitValue * 86400, + MassFlowUnit.GramPerHour => baseUnitValue * 3600, + MassFlowUnit.GramPerSecond => baseUnitValue, + MassFlowUnit.HectogramPerDay => (baseUnitValue * 86400) / 1e2d, + MassFlowUnit.HectogramPerSecond => (baseUnitValue) / 1e2d, + MassFlowUnit.KilogramPerDay => (baseUnitValue * 86400) / 1e3d, + MassFlowUnit.KilogramPerHour => baseUnitValue * 3.6, + MassFlowUnit.KilogramPerMinute => baseUnitValue * 0.06, + MassFlowUnit.KilogramPerSecond => (baseUnitValue) / 1e3d, + MassFlowUnit.MegagramPerDay => (baseUnitValue * 86400) / 1e6d, + MassFlowUnit.MegapoundPerDay => (baseUnitValue * 190.47936) / 1e6d, + MassFlowUnit.MegapoundPerHour => (baseUnitValue * 7.93664) / 1e6d, + MassFlowUnit.MegapoundPerMinute => (baseUnitValue * 0.132277) / 1e6d, + MassFlowUnit.MegapoundPerSecond => (baseUnitValue / 453.59237) / 1e6d, + MassFlowUnit.MicrogramPerDay => (baseUnitValue * 86400) / 1e-6d, + MassFlowUnit.MicrogramPerSecond => (baseUnitValue) / 1e-6d, + MassFlowUnit.MilligramPerDay => (baseUnitValue * 86400) / 1e-3d, + MassFlowUnit.MilligramPerSecond => (baseUnitValue) / 1e-3d, + MassFlowUnit.NanogramPerDay => (baseUnitValue * 86400) / 1e-9d, + MassFlowUnit.NanogramPerSecond => (baseUnitValue) / 1e-9d, + MassFlowUnit.PoundPerDay => baseUnitValue * 190.47936, + MassFlowUnit.PoundPerHour => baseUnitValue * 7.93664, + MassFlowUnit.PoundPerMinute => baseUnitValue * 0.132277, + MassFlowUnit.PoundPerSecond => baseUnitValue / 453.59237, + MassFlowUnit.ShortTonPerHour => baseUnitValue / 251.9957611, + MassFlowUnit.TonnePerDay => baseUnitValue * 0.0864000, + MassFlowUnit.TonnePerHour => baseUnitValue * 3.6 / 1000, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlux.g.cs index 74fabf7df2..6a2759fe82 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFlux.g.cs @@ -228,75 +228,75 @@ public static MassFlux From(double value, MassFluxUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFluxUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MassFlux ToUnit(MassFluxUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MassFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MassFluxUnit.GramPerHourPerSquareCentimeter => _value / 3.6e2, - MassFluxUnit.GramPerHourPerSquareMeter => _value / 3.6e6, - MassFluxUnit.GramPerHourPerSquareMillimeter => _value / 3.6e0, - MassFluxUnit.GramPerSecondPerSquareCentimeter => _value / 1e-1, - MassFluxUnit.GramPerSecondPerSquareMeter => _value / 1e3, - MassFluxUnit.GramPerSecondPerSquareMillimeter => _value / 1e-3, - MassFluxUnit.KilogramPerHourPerSquareCentimeter => (_value / 3.6e2) * 1e3d, - MassFluxUnit.KilogramPerHourPerSquareMeter => (_value / 3.6e6) * 1e3d, - MassFluxUnit.KilogramPerHourPerSquareMillimeter => (_value / 3.6e0) * 1e3d, - MassFluxUnit.KilogramPerSecondPerSquareCentimeter => (_value / 1e-1) * 1e3d, - MassFluxUnit.KilogramPerSecondPerSquareMeter => (_value / 1e3) * 1e3d, - MassFluxUnit.KilogramPerSecondPerSquareMillimeter => (_value / 1e-3) * 1e3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MassFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MassFluxUnit.GramPerHourPerSquareCentimeter => baseUnitValue * 3.6e2, - MassFluxUnit.GramPerHourPerSquareMeter => baseUnitValue * 3.6e6, - MassFluxUnit.GramPerHourPerSquareMillimeter => baseUnitValue * 3.6e0, - MassFluxUnit.GramPerSecondPerSquareCentimeter => baseUnitValue * 1e-1, - MassFluxUnit.GramPerSecondPerSquareMeter => baseUnitValue * 1e3, - MassFluxUnit.GramPerSecondPerSquareMillimeter => baseUnitValue * 1e-3, - MassFluxUnit.KilogramPerHourPerSquareCentimeter => (baseUnitValue * 3.6e2) / 1e3d, - MassFluxUnit.KilogramPerHourPerSquareMeter => (baseUnitValue * 3.6e6) / 1e3d, - MassFluxUnit.KilogramPerHourPerSquareMillimeter => (baseUnitValue * 3.6e0) / 1e3d, - MassFluxUnit.KilogramPerSecondPerSquareCentimeter => (baseUnitValue * 1e-1) / 1e3d, - MassFluxUnit.KilogramPerSecondPerSquareMeter => (baseUnitValue * 1e3) / 1e3d, - MassFluxUnit.KilogramPerSecondPerSquareMillimeter => (baseUnitValue * 1e-3) / 1e3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFluxUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MassFlux ToUnit(MassFluxUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MassFlux(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MassFluxUnit.GramPerHourPerSquareCentimeter => _value / 3.6e2, + MassFluxUnit.GramPerHourPerSquareMeter => _value / 3.6e6, + MassFluxUnit.GramPerHourPerSquareMillimeter => _value / 3.6e0, + MassFluxUnit.GramPerSecondPerSquareCentimeter => _value / 1e-1, + MassFluxUnit.GramPerSecondPerSquareMeter => _value / 1e3, + MassFluxUnit.GramPerSecondPerSquareMillimeter => _value / 1e-3, + MassFluxUnit.KilogramPerHourPerSquareCentimeter => (_value / 3.6e2) * 1e3d, + MassFluxUnit.KilogramPerHourPerSquareMeter => (_value / 3.6e6) * 1e3d, + MassFluxUnit.KilogramPerHourPerSquareMillimeter => (_value / 3.6e0) * 1e3d, + MassFluxUnit.KilogramPerSecondPerSquareCentimeter => (_value / 1e-1) * 1e3d, + MassFluxUnit.KilogramPerSecondPerSquareMeter => (_value / 1e3) * 1e3d, + MassFluxUnit.KilogramPerSecondPerSquareMillimeter => (_value / 1e-3) * 1e3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MassFluxUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MassFluxUnit.GramPerHourPerSquareCentimeter => baseUnitValue * 3.6e2, + MassFluxUnit.GramPerHourPerSquareMeter => baseUnitValue * 3.6e6, + MassFluxUnit.GramPerHourPerSquareMillimeter => baseUnitValue * 3.6e0, + MassFluxUnit.GramPerSecondPerSquareCentimeter => baseUnitValue * 1e-1, + MassFluxUnit.GramPerSecondPerSquareMeter => baseUnitValue * 1e3, + MassFluxUnit.GramPerSecondPerSquareMillimeter => baseUnitValue * 1e-3, + MassFluxUnit.KilogramPerHourPerSquareCentimeter => (baseUnitValue * 3.6e2) / 1e3d, + MassFluxUnit.KilogramPerHourPerSquareMeter => (baseUnitValue * 3.6e6) / 1e3d, + MassFluxUnit.KilogramPerHourPerSquareMillimeter => (baseUnitValue * 3.6e0) / 1e3d, + MassFluxUnit.KilogramPerSecondPerSquareCentimeter => (baseUnitValue * 1e-1) / 1e3d, + MassFluxUnit.KilogramPerSecondPerSquareMeter => (baseUnitValue * 1e3) / 1e3d, + MassFluxUnit.KilogramPerSecondPerSquareMillimeter => (baseUnitValue * 1e-3) / 1e3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFraction.g.cs index 2c1698db6f..26ca670405 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassFraction.g.cs @@ -363,99 +363,99 @@ public static MassFraction From(double value, MassFractionUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFractionUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MassFraction ToUnit(MassFractionUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MassFraction(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MassFractionUnit.CentigramPerGram => (_value) * 1e-2d, - MassFractionUnit.CentigramPerKilogram => (_value / 1e3) * 1e-2d, - MassFractionUnit.DecagramPerGram => (_value) * 1e1d, - MassFractionUnit.DecagramPerKilogram => (_value / 1e3) * 1e1d, - MassFractionUnit.DecigramPerGram => (_value) * 1e-1d, - MassFractionUnit.DecigramPerKilogram => (_value / 1e3) * 1e-1d, - MassFractionUnit.DecimalFraction => _value, - MassFractionUnit.GramPerGram => _value, - MassFractionUnit.GramPerKilogram => _value / 1e3, - MassFractionUnit.HectogramPerGram => (_value) * 1e2d, - MassFractionUnit.HectogramPerKilogram => (_value / 1e3) * 1e2d, - MassFractionUnit.KilogramPerGram => (_value) * 1e3d, - MassFractionUnit.KilogramPerKilogram => (_value / 1e3) * 1e3d, - MassFractionUnit.MicrogramPerGram => (_value) * 1e-6d, - MassFractionUnit.MicrogramPerKilogram => (_value / 1e3) * 1e-6d, - MassFractionUnit.MilligramPerGram => (_value) * 1e-3d, - MassFractionUnit.MilligramPerKilogram => (_value / 1e3) * 1e-3d, - MassFractionUnit.NanogramPerGram => (_value) * 1e-9d, - MassFractionUnit.NanogramPerKilogram => (_value / 1e3) * 1e-9d, - MassFractionUnit.PartPerBillion => _value / 1e9, - MassFractionUnit.PartPerMillion => _value / 1e6, - MassFractionUnit.PartPerThousand => _value / 1e3, - MassFractionUnit.PartPerTrillion => _value / 1e12, - MassFractionUnit.Percent => _value / 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MassFractionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MassFractionUnit.CentigramPerGram => (baseUnitValue) / 1e-2d, - MassFractionUnit.CentigramPerKilogram => (baseUnitValue * 1e3) / 1e-2d, - MassFractionUnit.DecagramPerGram => (baseUnitValue) / 1e1d, - MassFractionUnit.DecagramPerKilogram => (baseUnitValue * 1e3) / 1e1d, - MassFractionUnit.DecigramPerGram => (baseUnitValue) / 1e-1d, - MassFractionUnit.DecigramPerKilogram => (baseUnitValue * 1e3) / 1e-1d, - MassFractionUnit.DecimalFraction => baseUnitValue, - MassFractionUnit.GramPerGram => baseUnitValue, - MassFractionUnit.GramPerKilogram => baseUnitValue * 1e3, - MassFractionUnit.HectogramPerGram => (baseUnitValue) / 1e2d, - MassFractionUnit.HectogramPerKilogram => (baseUnitValue * 1e3) / 1e2d, - MassFractionUnit.KilogramPerGram => (baseUnitValue) / 1e3d, - MassFractionUnit.KilogramPerKilogram => (baseUnitValue * 1e3) / 1e3d, - MassFractionUnit.MicrogramPerGram => (baseUnitValue) / 1e-6d, - MassFractionUnit.MicrogramPerKilogram => (baseUnitValue * 1e3) / 1e-6d, - MassFractionUnit.MilligramPerGram => (baseUnitValue) / 1e-3d, - MassFractionUnit.MilligramPerKilogram => (baseUnitValue * 1e3) / 1e-3d, - MassFractionUnit.NanogramPerGram => (baseUnitValue) / 1e-9d, - MassFractionUnit.NanogramPerKilogram => (baseUnitValue * 1e3) / 1e-9d, - MassFractionUnit.PartPerBillion => baseUnitValue * 1e9, - MassFractionUnit.PartPerMillion => baseUnitValue * 1e6, - MassFractionUnit.PartPerThousand => baseUnitValue * 1e3, - MassFractionUnit.PartPerTrillion => baseUnitValue * 1e12, - MassFractionUnit.Percent => baseUnitValue * 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassFractionUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MassFraction ToUnit(MassFractionUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MassFraction(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MassFractionUnit.CentigramPerGram => (_value) * 1e-2d, + MassFractionUnit.CentigramPerKilogram => (_value / 1e3) * 1e-2d, + MassFractionUnit.DecagramPerGram => (_value) * 1e1d, + MassFractionUnit.DecagramPerKilogram => (_value / 1e3) * 1e1d, + MassFractionUnit.DecigramPerGram => (_value) * 1e-1d, + MassFractionUnit.DecigramPerKilogram => (_value / 1e3) * 1e-1d, + MassFractionUnit.DecimalFraction => _value, + MassFractionUnit.GramPerGram => _value, + MassFractionUnit.GramPerKilogram => _value / 1e3, + MassFractionUnit.HectogramPerGram => (_value) * 1e2d, + MassFractionUnit.HectogramPerKilogram => (_value / 1e3) * 1e2d, + MassFractionUnit.KilogramPerGram => (_value) * 1e3d, + MassFractionUnit.KilogramPerKilogram => (_value / 1e3) * 1e3d, + MassFractionUnit.MicrogramPerGram => (_value) * 1e-6d, + MassFractionUnit.MicrogramPerKilogram => (_value / 1e3) * 1e-6d, + MassFractionUnit.MilligramPerGram => (_value) * 1e-3d, + MassFractionUnit.MilligramPerKilogram => (_value / 1e3) * 1e-3d, + MassFractionUnit.NanogramPerGram => (_value) * 1e-9d, + MassFractionUnit.NanogramPerKilogram => (_value / 1e3) * 1e-9d, + MassFractionUnit.PartPerBillion => _value / 1e9, + MassFractionUnit.PartPerMillion => _value / 1e6, + MassFractionUnit.PartPerThousand => _value / 1e3, + MassFractionUnit.PartPerTrillion => _value / 1e12, + MassFractionUnit.Percent => _value / 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MassFractionUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MassFractionUnit.CentigramPerGram => (baseUnitValue) / 1e-2d, + MassFractionUnit.CentigramPerKilogram => (baseUnitValue * 1e3) / 1e-2d, + MassFractionUnit.DecagramPerGram => (baseUnitValue) / 1e1d, + MassFractionUnit.DecagramPerKilogram => (baseUnitValue * 1e3) / 1e1d, + MassFractionUnit.DecigramPerGram => (baseUnitValue) / 1e-1d, + MassFractionUnit.DecigramPerKilogram => (baseUnitValue * 1e3) / 1e-1d, + MassFractionUnit.DecimalFraction => baseUnitValue, + MassFractionUnit.GramPerGram => baseUnitValue, + MassFractionUnit.GramPerKilogram => baseUnitValue * 1e3, + MassFractionUnit.HectogramPerGram => (baseUnitValue) / 1e2d, + MassFractionUnit.HectogramPerKilogram => (baseUnitValue * 1e3) / 1e2d, + MassFractionUnit.KilogramPerGram => (baseUnitValue) / 1e3d, + MassFractionUnit.KilogramPerKilogram => (baseUnitValue * 1e3) / 1e3d, + MassFractionUnit.MicrogramPerGram => (baseUnitValue) / 1e-6d, + MassFractionUnit.MicrogramPerKilogram => (baseUnitValue * 1e3) / 1e-6d, + MassFractionUnit.MilligramPerGram => (baseUnitValue) / 1e-3d, + MassFractionUnit.MilligramPerKilogram => (baseUnitValue * 1e3) / 1e-3d, + MassFractionUnit.NanogramPerGram => (baseUnitValue) / 1e-9d, + MassFractionUnit.NanogramPerKilogram => (baseUnitValue * 1e3) / 1e-9d, + MassFractionUnit.PartPerBillion => baseUnitValue * 1e9, + MassFractionUnit.PartPerMillion => baseUnitValue * 1e6, + MassFractionUnit.PartPerThousand => baseUnitValue * 1e3, + MassFractionUnit.PartPerTrillion => baseUnitValue * 1e12, + MassFractionUnit.Percent => baseUnitValue * 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index eb58296af7..dc62d88176 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -404,107 +404,107 @@ public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassMomentOfInertiaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MassMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MassMomentOfInertiaUnit.GramSquareCentimeter => _value / 1e7, - MassMomentOfInertiaUnit.GramSquareDecimeter => _value / 1e5, - MassMomentOfInertiaUnit.GramSquareMeter => _value / 1e3, - MassMomentOfInertiaUnit.GramSquareMillimeter => _value / 1e9, - MassMomentOfInertiaUnit.KilogramSquareCentimeter => (_value / 1e7) * 1e3d, - MassMomentOfInertiaUnit.KilogramSquareDecimeter => (_value / 1e5) * 1e3d, - MassMomentOfInertiaUnit.KilogramSquareMeter => (_value / 1e3) * 1e3d, - MassMomentOfInertiaUnit.KilogramSquareMillimeter => (_value / 1e9) * 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareCentimeter => (_value / 1e1) * 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareDecimeter => (_value / 1e-1) * 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareMeter => (_value / 1e-3) * 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareMilimeter => (_value / 1e3) * 1e3d, - MassMomentOfInertiaUnit.MegatonneSquareCentimeter => (_value / 1e1) * 1e6d, - MassMomentOfInertiaUnit.MegatonneSquareDecimeter => (_value / 1e-1) * 1e6d, - MassMomentOfInertiaUnit.MegatonneSquareMeter => (_value / 1e-3) * 1e6d, - MassMomentOfInertiaUnit.MegatonneSquareMilimeter => (_value / 1e3) * 1e6d, - MassMomentOfInertiaUnit.MilligramSquareCentimeter => (_value / 1e7) * 1e-3d, - MassMomentOfInertiaUnit.MilligramSquareDecimeter => (_value / 1e5) * 1e-3d, - MassMomentOfInertiaUnit.MilligramSquareMeter => (_value / 1e3) * 1e-3d, - MassMomentOfInertiaUnit.MilligramSquareMillimeter => (_value / 1e9) * 1e-3d, - MassMomentOfInertiaUnit.PoundSquareFoot => _value * 4.21401101e-2, - MassMomentOfInertiaUnit.PoundSquareInch => _value * 2.9263965e-4, - MassMomentOfInertiaUnit.SlugSquareFoot => _value * 1.3558179619, - MassMomentOfInertiaUnit.SlugSquareInch => _value * 9.41540242e-3, - MassMomentOfInertiaUnit.TonneSquareCentimeter => _value / 1e1, - MassMomentOfInertiaUnit.TonneSquareDecimeter => _value / 1e-1, - MassMomentOfInertiaUnit.TonneSquareMeter => _value / 1e-3, - MassMomentOfInertiaUnit.TonneSquareMilimeter => _value / 1e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MassMomentOfInertiaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MassMomentOfInertiaUnit.GramSquareCentimeter => baseUnitValue * 1e7, - MassMomentOfInertiaUnit.GramSquareDecimeter => baseUnitValue * 1e5, - MassMomentOfInertiaUnit.GramSquareMeter => baseUnitValue * 1e3, - MassMomentOfInertiaUnit.GramSquareMillimeter => baseUnitValue * 1e9, - MassMomentOfInertiaUnit.KilogramSquareCentimeter => (baseUnitValue * 1e7) / 1e3d, - MassMomentOfInertiaUnit.KilogramSquareDecimeter => (baseUnitValue * 1e5) / 1e3d, - MassMomentOfInertiaUnit.KilogramSquareMeter => (baseUnitValue * 1e3) / 1e3d, - MassMomentOfInertiaUnit.KilogramSquareMillimeter => (baseUnitValue * 1e9) / 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareCentimeter => (baseUnitValue * 1e1) / 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareDecimeter => (baseUnitValue * 1e-1) / 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareMeter => (baseUnitValue * 1e-3) / 1e3d, - MassMomentOfInertiaUnit.KilotonneSquareMilimeter => (baseUnitValue * 1e3) / 1e3d, - MassMomentOfInertiaUnit.MegatonneSquareCentimeter => (baseUnitValue * 1e1) / 1e6d, - MassMomentOfInertiaUnit.MegatonneSquareDecimeter => (baseUnitValue * 1e-1) / 1e6d, - MassMomentOfInertiaUnit.MegatonneSquareMeter => (baseUnitValue * 1e-3) / 1e6d, - MassMomentOfInertiaUnit.MegatonneSquareMilimeter => (baseUnitValue * 1e3) / 1e6d, - MassMomentOfInertiaUnit.MilligramSquareCentimeter => (baseUnitValue * 1e7) / 1e-3d, - MassMomentOfInertiaUnit.MilligramSquareDecimeter => (baseUnitValue * 1e5) / 1e-3d, - MassMomentOfInertiaUnit.MilligramSquareMeter => (baseUnitValue * 1e3) / 1e-3d, - MassMomentOfInertiaUnit.MilligramSquareMillimeter => (baseUnitValue * 1e9) / 1e-3d, - MassMomentOfInertiaUnit.PoundSquareFoot => baseUnitValue / 4.21401101e-2, - MassMomentOfInertiaUnit.PoundSquareInch => baseUnitValue / 2.9263965e-4, - MassMomentOfInertiaUnit.SlugSquareFoot => baseUnitValue / 1.3558179619, - MassMomentOfInertiaUnit.SlugSquareInch => baseUnitValue / 9.41540242e-3, - MassMomentOfInertiaUnit.TonneSquareCentimeter => baseUnitValue * 1e1, - MassMomentOfInertiaUnit.TonneSquareDecimeter => baseUnitValue * 1e-1, - MassMomentOfInertiaUnit.TonneSquareMeter => baseUnitValue * 1e-3, - MassMomentOfInertiaUnit.TonneSquareMilimeter => baseUnitValue * 1e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MassMomentOfInertiaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MassMomentOfInertia(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MassMomentOfInertiaUnit.GramSquareCentimeter => _value / 1e7, + MassMomentOfInertiaUnit.GramSquareDecimeter => _value / 1e5, + MassMomentOfInertiaUnit.GramSquareMeter => _value / 1e3, + MassMomentOfInertiaUnit.GramSquareMillimeter => _value / 1e9, + MassMomentOfInertiaUnit.KilogramSquareCentimeter => (_value / 1e7) * 1e3d, + MassMomentOfInertiaUnit.KilogramSquareDecimeter => (_value / 1e5) * 1e3d, + MassMomentOfInertiaUnit.KilogramSquareMeter => (_value / 1e3) * 1e3d, + MassMomentOfInertiaUnit.KilogramSquareMillimeter => (_value / 1e9) * 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareCentimeter => (_value / 1e1) * 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareDecimeter => (_value / 1e-1) * 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareMeter => (_value / 1e-3) * 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareMilimeter => (_value / 1e3) * 1e3d, + MassMomentOfInertiaUnit.MegatonneSquareCentimeter => (_value / 1e1) * 1e6d, + MassMomentOfInertiaUnit.MegatonneSquareDecimeter => (_value / 1e-1) * 1e6d, + MassMomentOfInertiaUnit.MegatonneSquareMeter => (_value / 1e-3) * 1e6d, + MassMomentOfInertiaUnit.MegatonneSquareMilimeter => (_value / 1e3) * 1e6d, + MassMomentOfInertiaUnit.MilligramSquareCentimeter => (_value / 1e7) * 1e-3d, + MassMomentOfInertiaUnit.MilligramSquareDecimeter => (_value / 1e5) * 1e-3d, + MassMomentOfInertiaUnit.MilligramSquareMeter => (_value / 1e3) * 1e-3d, + MassMomentOfInertiaUnit.MilligramSquareMillimeter => (_value / 1e9) * 1e-3d, + MassMomentOfInertiaUnit.PoundSquareFoot => _value * 4.21401101e-2, + MassMomentOfInertiaUnit.PoundSquareInch => _value * 2.9263965e-4, + MassMomentOfInertiaUnit.SlugSquareFoot => _value * 1.3558179619, + MassMomentOfInertiaUnit.SlugSquareInch => _value * 9.41540242e-3, + MassMomentOfInertiaUnit.TonneSquareCentimeter => _value / 1e1, + MassMomentOfInertiaUnit.TonneSquareDecimeter => _value / 1e-1, + MassMomentOfInertiaUnit.TonneSquareMeter => _value / 1e-3, + MassMomentOfInertiaUnit.TonneSquareMilimeter => _value / 1e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MassMomentOfInertiaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MassMomentOfInertiaUnit.GramSquareCentimeter => baseUnitValue * 1e7, + MassMomentOfInertiaUnit.GramSquareDecimeter => baseUnitValue * 1e5, + MassMomentOfInertiaUnit.GramSquareMeter => baseUnitValue * 1e3, + MassMomentOfInertiaUnit.GramSquareMillimeter => baseUnitValue * 1e9, + MassMomentOfInertiaUnit.KilogramSquareCentimeter => (baseUnitValue * 1e7) / 1e3d, + MassMomentOfInertiaUnit.KilogramSquareDecimeter => (baseUnitValue * 1e5) / 1e3d, + MassMomentOfInertiaUnit.KilogramSquareMeter => (baseUnitValue * 1e3) / 1e3d, + MassMomentOfInertiaUnit.KilogramSquareMillimeter => (baseUnitValue * 1e9) / 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareCentimeter => (baseUnitValue * 1e1) / 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareDecimeter => (baseUnitValue * 1e-1) / 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareMeter => (baseUnitValue * 1e-3) / 1e3d, + MassMomentOfInertiaUnit.KilotonneSquareMilimeter => (baseUnitValue * 1e3) / 1e3d, + MassMomentOfInertiaUnit.MegatonneSquareCentimeter => (baseUnitValue * 1e1) / 1e6d, + MassMomentOfInertiaUnit.MegatonneSquareDecimeter => (baseUnitValue * 1e-1) / 1e6d, + MassMomentOfInertiaUnit.MegatonneSquareMeter => (baseUnitValue * 1e-3) / 1e6d, + MassMomentOfInertiaUnit.MegatonneSquareMilimeter => (baseUnitValue * 1e3) / 1e6d, + MassMomentOfInertiaUnit.MilligramSquareCentimeter => (baseUnitValue * 1e7) / 1e-3d, + MassMomentOfInertiaUnit.MilligramSquareDecimeter => (baseUnitValue * 1e5) / 1e-3d, + MassMomentOfInertiaUnit.MilligramSquareMeter => (baseUnitValue * 1e3) / 1e-3d, + MassMomentOfInertiaUnit.MilligramSquareMillimeter => (baseUnitValue * 1e9) / 1e-3d, + MassMomentOfInertiaUnit.PoundSquareFoot => baseUnitValue / 4.21401101e-2, + MassMomentOfInertiaUnit.PoundSquareInch => baseUnitValue / 2.9263965e-4, + MassMomentOfInertiaUnit.SlugSquareFoot => baseUnitValue / 1.3558179619, + MassMomentOfInertiaUnit.SlugSquareInch => baseUnitValue / 9.41540242e-3, + MassMomentOfInertiaUnit.TonneSquareCentimeter => baseUnitValue * 1e1, + MassMomentOfInertiaUnit.TonneSquareDecimeter => baseUnitValue * 1e-1, + MassMomentOfInertiaUnit.TonneSquareMeter => baseUnitValue * 1e-3, + MassMomentOfInertiaUnit.TonneSquareMilimeter => baseUnitValue * 1e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEnergy.g.cs index bcb3524c17..9a1ae12634 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -129,57 +129,57 @@ public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEnergyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MolarEnergy ToUnit(MolarEnergyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MolarEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MolarEnergyUnit.JoulePerMole => _value, - MolarEnergyUnit.KilojoulePerMole => (_value) * 1e3d, - MolarEnergyUnit.MegajoulePerMole => (_value) * 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MolarEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MolarEnergyUnit.JoulePerMole => baseUnitValue, - MolarEnergyUnit.KilojoulePerMole => (baseUnitValue) / 1e3d, - MolarEnergyUnit.MegajoulePerMole => (baseUnitValue) / 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarEnergyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MolarEnergy ToUnit(MolarEnergyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MolarEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MolarEnergyUnit.JoulePerMole => _value, + MolarEnergyUnit.KilojoulePerMole => (_value) * 1e3d, + MolarEnergyUnit.MegajoulePerMole => (_value) * 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MolarEnergyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MolarEnergyUnit.JoulePerMole => baseUnitValue, + MolarEnergyUnit.KilojoulePerMole => (baseUnitValue) / 1e3d, + MolarEnergyUnit.MegajoulePerMole => (baseUnitValue) / 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEntropy.g.cs index f9828af81e..6e38418c2b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -129,57 +129,57 @@ public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEntropyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MolarEntropy ToUnit(MolarEntropyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MolarEntropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MolarEntropyUnit.JoulePerMoleKelvin => _value, - MolarEntropyUnit.KilojoulePerMoleKelvin => (_value) * 1e3d, - MolarEntropyUnit.MegajoulePerMoleKelvin => (_value) * 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MolarEntropyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MolarEntropyUnit.JoulePerMoleKelvin => baseUnitValue, - MolarEntropyUnit.KilojoulePerMoleKelvin => (baseUnitValue) / 1e3d, - MolarEntropyUnit.MegajoulePerMoleKelvin => (baseUnitValue) / 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarEntropyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MolarEntropy ToUnit(MolarEntropyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MolarEntropy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MolarEntropyUnit.JoulePerMoleKelvin => _value, + MolarEntropyUnit.KilojoulePerMoleKelvin => (_value) * 1e3d, + MolarEntropyUnit.MegajoulePerMoleKelvin => (_value) * 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MolarEntropyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MolarEntropyUnit.JoulePerMoleKelvin => baseUnitValue, + MolarEntropyUnit.KilojoulePerMoleKelvin => (baseUnitValue) / 1e3d, + MolarEntropyUnit.MegajoulePerMoleKelvin => (baseUnitValue) / 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarMass.g.cs index 492ca9893b..8134422826 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/MolarMass.g.cs @@ -228,75 +228,75 @@ public static MolarMass From(double value, MolarMassUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarMassUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public MolarMass ToUnit(MolarMassUnit unit) - { - var convertedValue = GetValueAs(unit); - return new MolarMass(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MolarMassUnit.CentigramPerMole => (_value / 1e3) * 1e-2d, - MolarMassUnit.DecagramPerMole => (_value / 1e3) * 1e1d, - MolarMassUnit.DecigramPerMole => (_value / 1e3) * 1e-1d, - MolarMassUnit.GramPerMole => _value / 1e3, - MolarMassUnit.HectogramPerMole => (_value / 1e3) * 1e2d, - MolarMassUnit.KilogramPerMole => (_value / 1e3) * 1e3d, - MolarMassUnit.KilopoundPerMole => (_value * 0.45359237) * 1e3d, - MolarMassUnit.MegapoundPerMole => (_value * 0.45359237) * 1e6d, - MolarMassUnit.MicrogramPerMole => (_value / 1e3) * 1e-6d, - MolarMassUnit.MilligramPerMole => (_value / 1e3) * 1e-3d, - MolarMassUnit.NanogramPerMole => (_value / 1e3) * 1e-9d, - MolarMassUnit.PoundPerMole => _value * 0.45359237, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MolarMassUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MolarMassUnit.CentigramPerMole => (baseUnitValue * 1e3) / 1e-2d, - MolarMassUnit.DecagramPerMole => (baseUnitValue * 1e3) / 1e1d, - MolarMassUnit.DecigramPerMole => (baseUnitValue * 1e3) / 1e-1d, - MolarMassUnit.GramPerMole => baseUnitValue * 1e3, - MolarMassUnit.HectogramPerMole => (baseUnitValue * 1e3) / 1e2d, - MolarMassUnit.KilogramPerMole => (baseUnitValue * 1e3) / 1e3d, - MolarMassUnit.KilopoundPerMole => (baseUnitValue / 0.45359237) / 1e3d, - MolarMassUnit.MegapoundPerMole => (baseUnitValue / 0.45359237) / 1e6d, - MolarMassUnit.MicrogramPerMole => (baseUnitValue * 1e3) / 1e-6d, - MolarMassUnit.MilligramPerMole => (baseUnitValue * 1e3) / 1e-3d, - MolarMassUnit.NanogramPerMole => (baseUnitValue * 1e3) / 1e-9d, - MolarMassUnit.PoundPerMole => baseUnitValue / 0.45359237, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarMassUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public MolarMass ToUnit(MolarMassUnit unit) + { + var convertedValue = GetValueAs(unit); + return new MolarMass(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MolarMassUnit.CentigramPerMole => (_value / 1e3) * 1e-2d, + MolarMassUnit.DecagramPerMole => (_value / 1e3) * 1e1d, + MolarMassUnit.DecigramPerMole => (_value / 1e3) * 1e-1d, + MolarMassUnit.GramPerMole => _value / 1e3, + MolarMassUnit.HectogramPerMole => (_value / 1e3) * 1e2d, + MolarMassUnit.KilogramPerMole => (_value / 1e3) * 1e3d, + MolarMassUnit.KilopoundPerMole => (_value * 0.45359237) * 1e3d, + MolarMassUnit.MegapoundPerMole => (_value * 0.45359237) * 1e6d, + MolarMassUnit.MicrogramPerMole => (_value / 1e3) * 1e-6d, + MolarMassUnit.MilligramPerMole => (_value / 1e3) * 1e-3d, + MolarMassUnit.NanogramPerMole => (_value / 1e3) * 1e-9d, + MolarMassUnit.PoundPerMole => _value * 0.45359237, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MolarMassUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MolarMassUnit.CentigramPerMole => (baseUnitValue * 1e3) / 1e-2d, + MolarMassUnit.DecagramPerMole => (baseUnitValue * 1e3) / 1e1d, + MolarMassUnit.DecigramPerMole => (baseUnitValue * 1e3) / 1e-1d, + MolarMassUnit.GramPerMole => baseUnitValue * 1e3, + MolarMassUnit.HectogramPerMole => (baseUnitValue * 1e3) / 1e2d, + MolarMassUnit.KilogramPerMole => (baseUnitValue * 1e3) / 1e3d, + MolarMassUnit.KilopoundPerMole => (baseUnitValue / 0.45359237) / 1e3d, + MolarMassUnit.MegapoundPerMole => (baseUnitValue / 0.45359237) / 1e6d, + MolarMassUnit.MicrogramPerMole => (baseUnitValue * 1e3) / 1e-6d, + MolarMassUnit.MilligramPerMole => (baseUnitValue * 1e3) / 1e-3d, + MolarMassUnit.NanogramPerMole => (baseUnitValue * 1e3) / 1e-9d, + MolarMassUnit.PoundPerMole => baseUnitValue / 0.45359237, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molarity.g.cs index 35b53e883f..f467869488 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Molarity.g.cs @@ -198,85 +198,85 @@ public static Molarity From(double value, MolarityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Molarity ToUnit(MolarityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Molarity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - MolarityUnit.CentimolePerLiter => (_value / 1e-3) * 1e-2d, - MolarityUnit.CentimolesPerLiter => (_value / 1e-3) * 1e-2d, - MolarityUnit.DecimolePerLiter => (_value / 1e-3) * 1e-1d, - MolarityUnit.DecimolesPerLiter => (_value / 1e-3) * 1e-1d, - MolarityUnit.FemtomolePerLiter => (_value / 1e-3) * 1e-15d, - MolarityUnit.MicromolePerLiter => (_value / 1e-3) * 1e-6d, - MolarityUnit.MicromolesPerLiter => (_value / 1e-3) * 1e-6d, - MolarityUnit.MillimolePerLiter => (_value / 1e-3) * 1e-3d, - MolarityUnit.MillimolesPerLiter => (_value / 1e-3) * 1e-3d, - MolarityUnit.MolePerCubicMeter => _value, - MolarityUnit.MolePerLiter => _value / 1e-3, - MolarityUnit.MolesPerCubicMeter => _value, - MolarityUnit.MolesPerLiter => _value / 1e-3, - MolarityUnit.NanomolePerLiter => (_value / 1e-3) * 1e-9d, - MolarityUnit.NanomolesPerLiter => (_value / 1e-3) * 1e-9d, - MolarityUnit.PicomolePerLiter => (_value / 1e-3) * 1e-12d, - MolarityUnit.PicomolesPerLiter => (_value / 1e-3) * 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(MolarityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - MolarityUnit.CentimolePerLiter => (baseUnitValue * 1e-3) / 1e-2d, - MolarityUnit.CentimolesPerLiter => (baseUnitValue * 1e-3) / 1e-2d, - MolarityUnit.DecimolePerLiter => (baseUnitValue * 1e-3) / 1e-1d, - MolarityUnit.DecimolesPerLiter => (baseUnitValue * 1e-3) / 1e-1d, - MolarityUnit.FemtomolePerLiter => (baseUnitValue * 1e-3) / 1e-15d, - MolarityUnit.MicromolePerLiter => (baseUnitValue * 1e-3) / 1e-6d, - MolarityUnit.MicromolesPerLiter => (baseUnitValue * 1e-3) / 1e-6d, - MolarityUnit.MillimolePerLiter => (baseUnitValue * 1e-3) / 1e-3d, - MolarityUnit.MillimolesPerLiter => (baseUnitValue * 1e-3) / 1e-3d, - MolarityUnit.MolePerCubicMeter => baseUnitValue, - MolarityUnit.MolePerLiter => baseUnitValue * 1e-3, - MolarityUnit.MolesPerCubicMeter => baseUnitValue, - MolarityUnit.MolesPerLiter => baseUnitValue * 1e-3, - MolarityUnit.NanomolePerLiter => (baseUnitValue * 1e-3) / 1e-9d, - MolarityUnit.NanomolesPerLiter => (baseUnitValue * 1e-3) / 1e-9d, - MolarityUnit.PicomolePerLiter => (baseUnitValue * 1e-3) / 1e-12d, - MolarityUnit.PicomolesPerLiter => (baseUnitValue * 1e-3) / 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(MolarityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Molarity ToUnit(MolarityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Molarity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + MolarityUnit.CentimolePerLiter => (_value / 1e-3) * 1e-2d, + MolarityUnit.CentimolesPerLiter => (_value / 1e-3) * 1e-2d, + MolarityUnit.DecimolePerLiter => (_value / 1e-3) * 1e-1d, + MolarityUnit.DecimolesPerLiter => (_value / 1e-3) * 1e-1d, + MolarityUnit.FemtomolePerLiter => (_value / 1e-3) * 1e-15d, + MolarityUnit.MicromolePerLiter => (_value / 1e-3) * 1e-6d, + MolarityUnit.MicromolesPerLiter => (_value / 1e-3) * 1e-6d, + MolarityUnit.MillimolePerLiter => (_value / 1e-3) * 1e-3d, + MolarityUnit.MillimolesPerLiter => (_value / 1e-3) * 1e-3d, + MolarityUnit.MolePerCubicMeter => _value, + MolarityUnit.MolePerLiter => _value / 1e-3, + MolarityUnit.MolesPerCubicMeter => _value, + MolarityUnit.MolesPerLiter => _value / 1e-3, + MolarityUnit.NanomolePerLiter => (_value / 1e-3) * 1e-9d, + MolarityUnit.NanomolesPerLiter => (_value / 1e-3) * 1e-9d, + MolarityUnit.PicomolePerLiter => (_value / 1e-3) * 1e-12d, + MolarityUnit.PicomolesPerLiter => (_value / 1e-3) * 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(MolarityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + MolarityUnit.CentimolePerLiter => (baseUnitValue * 1e-3) / 1e-2d, + MolarityUnit.CentimolesPerLiter => (baseUnitValue * 1e-3) / 1e-2d, + MolarityUnit.DecimolePerLiter => (baseUnitValue * 1e-3) / 1e-1d, + MolarityUnit.DecimolesPerLiter => (baseUnitValue * 1e-3) / 1e-1d, + MolarityUnit.FemtomolePerLiter => (baseUnitValue * 1e-3) / 1e-15d, + MolarityUnit.MicromolePerLiter => (baseUnitValue * 1e-3) / 1e-6d, + MolarityUnit.MicromolesPerLiter => (baseUnitValue * 1e-3) / 1e-6d, + MolarityUnit.MillimolePerLiter => (baseUnitValue * 1e-3) / 1e-3d, + MolarityUnit.MillimolesPerLiter => (baseUnitValue * 1e-3) / 1e-3d, + MolarityUnit.MolePerCubicMeter => baseUnitValue, + MolarityUnit.MolePerLiter => baseUnitValue * 1e-3, + MolarityUnit.MolesPerCubicMeter => baseUnitValue, + MolarityUnit.MolesPerLiter => baseUnitValue * 1e-3, + MolarityUnit.NanomolePerLiter => (baseUnitValue * 1e-3) / 1e-9d, + MolarityUnit.NanomolesPerLiter => (baseUnitValue * 1e-3) / 1e-9d, + MolarityUnit.PicomolePerLiter => (baseUnitValue * 1e-3) / 1e-12d, + MolarityUnit.PicomolesPerLiter => (baseUnitValue * 1e-3) / 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permeability.g.cs index b054902b86..a98b0e85a0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permeability.g.cs @@ -110,53 +110,53 @@ public static Permeability From(double value, PermeabilityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermeabilityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Permeability ToUnit(PermeabilityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Permeability(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PermeabilityUnit.HenryPerMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PermeabilityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PermeabilityUnit.HenryPerMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PermeabilityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Permeability ToUnit(PermeabilityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Permeability(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PermeabilityUnit.HenryPerMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PermeabilityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PermeabilityUnit.HenryPerMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permittivity.g.cs index 34e98e4c76..2ca265a7d5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Permittivity.g.cs @@ -110,53 +110,53 @@ public static Permittivity From(double value, PermittivityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermittivityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Permittivity ToUnit(PermittivityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Permittivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PermittivityUnit.FaradPerMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PermittivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PermittivityUnit.FaradPerMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PermittivityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Permittivity ToUnit(PermittivityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Permittivity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PermittivityUnit.FaradPerMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PermittivityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PermittivityUnit.FaradPerMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PorousMediumPermeability.g.cs index bd21765293..67a765161c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PorousMediumPermeability.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// In fluid mechanics, permeability is the measure of the ability of a porous material to allow fluids to pass through it. + /// /// /// /// https://en.wikipedia.org/wiki/Permeability_(Earth_sciences) @@ -154,61 +154,61 @@ public static PorousMediumPermeability From(double value, PorousMediumPermeabili #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PorousMediumPermeabilityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new PorousMediumPermeability(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PorousMediumPermeabilityUnit.Darcy => _value * 9.869233e-13, - PorousMediumPermeabilityUnit.Microdarcy => (_value * 9.869233e-13) * 1e-6d, - PorousMediumPermeabilityUnit.Millidarcy => (_value * 9.869233e-13) * 1e-3d, - PorousMediumPermeabilityUnit.SquareCentimeter => _value * 1e-4, - PorousMediumPermeabilityUnit.SquareMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PorousMediumPermeabilityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PorousMediumPermeabilityUnit.Darcy => baseUnitValue / 9.869233e-13, - PorousMediumPermeabilityUnit.Microdarcy => (baseUnitValue / 9.869233e-13) / 1e-6d, - PorousMediumPermeabilityUnit.Millidarcy => (baseUnitValue / 9.869233e-13) / 1e-3d, - PorousMediumPermeabilityUnit.SquareCentimeter => baseUnitValue / 1e-4, - PorousMediumPermeabilityUnit.SquareMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PorousMediumPermeabilityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new PorousMediumPermeability(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PorousMediumPermeabilityUnit.Darcy => _value * 9.869233e-13, + PorousMediumPermeabilityUnit.Microdarcy => (_value * 9.869233e-13) * 1e-6d, + PorousMediumPermeabilityUnit.Millidarcy => (_value * 9.869233e-13) * 1e-3d, + PorousMediumPermeabilityUnit.SquareCentimeter => _value * 1e-4, + PorousMediumPermeabilityUnit.SquareMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PorousMediumPermeabilityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PorousMediumPermeabilityUnit.Darcy => baseUnitValue / 9.869233e-13, + PorousMediumPermeabilityUnit.Microdarcy => (baseUnitValue / 9.869233e-13) / 1e-6d, + PorousMediumPermeabilityUnit.Millidarcy => (baseUnitValue / 9.869233e-13) / 1e-3d, + PorousMediumPermeabilityUnit.SquareCentimeter => baseUnitValue / 1e-4, + PorousMediumPermeabilityUnit.SquareMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs index 002fbef780..e10cb3d208 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Power.g.cs @@ -382,103 +382,103 @@ public static Power From(double value, PowerUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Power ToUnit(PowerUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Power(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PowerUnit.BoilerHorsepower => _value * 9812.5d, - PowerUnit.BritishThermalUnitPerHour => _value * 0.293071d, - PowerUnit.Decawatt => (_value) * 1e1d, - PowerUnit.Deciwatt => (_value) * 1e-1d, - PowerUnit.ElectricalHorsepower => _value * 746d, - PowerUnit.Femtowatt => (_value) * 1e-15d, - PowerUnit.GigajoulePerHour => (_value / 3600d) * 1e9d, - PowerUnit.Gigawatt => (_value) * 1e9d, - PowerUnit.HydraulicHorsepower => _value * 745.69988145d, - PowerUnit.JoulePerHour => _value / 3600d, - PowerUnit.KilobritishThermalUnitPerHour => (_value * 0.293071d) * 1e3d, - PowerUnit.KilojoulePerHour => (_value / 3600d) * 1e3d, - PowerUnit.Kilowatt => (_value) * 1e3d, - PowerUnit.MechanicalHorsepower => _value * 745.69d, - PowerUnit.MegabritishThermalUnitPerHour => (_value * 0.293071d) * 1e6d, - PowerUnit.MegajoulePerHour => (_value / 3600d) * 1e6d, - PowerUnit.Megawatt => (_value) * 1e6d, - PowerUnit.MetricHorsepower => _value * 735.49875d, - PowerUnit.Microwatt => (_value) * 1e-6d, - PowerUnit.MillijoulePerHour => (_value / 3600d) * 1e-3d, - PowerUnit.Milliwatt => (_value) * 1e-3d, - PowerUnit.Nanowatt => (_value) * 1e-9d, - PowerUnit.Petawatt => (_value) * 1e15d, - PowerUnit.Picowatt => (_value) * 1e-12d, - PowerUnit.Terawatt => (_value) * 1e12d, - PowerUnit.Watt => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PowerUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PowerUnit.BoilerHorsepower => baseUnitValue / 9812.5d, - PowerUnit.BritishThermalUnitPerHour => baseUnitValue / 0.293071d, - PowerUnit.Decawatt => (baseUnitValue) / 1e1d, - PowerUnit.Deciwatt => (baseUnitValue) / 1e-1d, - PowerUnit.ElectricalHorsepower => baseUnitValue / 746d, - PowerUnit.Femtowatt => (baseUnitValue) / 1e-15d, - PowerUnit.GigajoulePerHour => (baseUnitValue * 3600d) / 1e9d, - PowerUnit.Gigawatt => (baseUnitValue) / 1e9d, - PowerUnit.HydraulicHorsepower => baseUnitValue / 745.69988145d, - PowerUnit.JoulePerHour => baseUnitValue * 3600d, - PowerUnit.KilobritishThermalUnitPerHour => (baseUnitValue / 0.293071d) / 1e3d, - PowerUnit.KilojoulePerHour => (baseUnitValue * 3600d) / 1e3d, - PowerUnit.Kilowatt => (baseUnitValue) / 1e3d, - PowerUnit.MechanicalHorsepower => baseUnitValue / 745.69d, - PowerUnit.MegabritishThermalUnitPerHour => (baseUnitValue / 0.293071d) / 1e6d, - PowerUnit.MegajoulePerHour => (baseUnitValue * 3600d) / 1e6d, - PowerUnit.Megawatt => (baseUnitValue) / 1e6d, - PowerUnit.MetricHorsepower => baseUnitValue / 735.49875d, - PowerUnit.Microwatt => (baseUnitValue) / 1e-6d, - PowerUnit.MillijoulePerHour => (baseUnitValue * 3600d) / 1e-3d, - PowerUnit.Milliwatt => (baseUnitValue) / 1e-3d, - PowerUnit.Nanowatt => (baseUnitValue) / 1e-9d, - PowerUnit.Petawatt => (baseUnitValue) / 1e15d, - PowerUnit.Picowatt => (baseUnitValue) / 1e-12d, - PowerUnit.Terawatt => (baseUnitValue) / 1e12d, - PowerUnit.Watt => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Power ToUnit(PowerUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Power(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PowerUnit.BoilerHorsepower => _value * 9812.5d, + PowerUnit.BritishThermalUnitPerHour => _value * 0.29307107017d, + PowerUnit.Decawatt => (_value) * 1e1d, + PowerUnit.Deciwatt => (_value) * 1e-1d, + PowerUnit.ElectricalHorsepower => _value * 746d, + PowerUnit.Femtowatt => (_value) * 1e-15d, + PowerUnit.GigajoulePerHour => (_value / 3600d) * 1e9d, + PowerUnit.Gigawatt => (_value) * 1e9d, + PowerUnit.HydraulicHorsepower => _value * 745.69988145d, + PowerUnit.JoulePerHour => _value / 3600d, + PowerUnit.KilobritishThermalUnitPerHour => (_value * 0.29307107017d) * 1e3d, + PowerUnit.KilojoulePerHour => (_value / 3600d) * 1e3d, + PowerUnit.Kilowatt => (_value) * 1e3d, + PowerUnit.MechanicalHorsepower => _value * 745.69d, + PowerUnit.MegabritishThermalUnitPerHour => (_value * 0.29307107017d) * 1e6d, + PowerUnit.MegajoulePerHour => (_value / 3600d) * 1e6d, + PowerUnit.Megawatt => (_value) * 1e6d, + PowerUnit.MetricHorsepower => _value * 735.49875d, + PowerUnit.Microwatt => (_value) * 1e-6d, + PowerUnit.MillijoulePerHour => (_value / 3600d) * 1e-3d, + PowerUnit.Milliwatt => (_value) * 1e-3d, + PowerUnit.Nanowatt => (_value) * 1e-9d, + PowerUnit.Petawatt => (_value) * 1e15d, + PowerUnit.Picowatt => (_value) * 1e-12d, + PowerUnit.Terawatt => (_value) * 1e12d, + PowerUnit.Watt => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PowerUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PowerUnit.BoilerHorsepower => baseUnitValue / 9812.5d, + PowerUnit.BritishThermalUnitPerHour => baseUnitValue / 0.29307107017d, + PowerUnit.Decawatt => (baseUnitValue) / 1e1d, + PowerUnit.Deciwatt => (baseUnitValue) / 1e-1d, + PowerUnit.ElectricalHorsepower => baseUnitValue / 746d, + PowerUnit.Femtowatt => (baseUnitValue) / 1e-15d, + PowerUnit.GigajoulePerHour => (baseUnitValue * 3600d) / 1e9d, + PowerUnit.Gigawatt => (baseUnitValue) / 1e9d, + PowerUnit.HydraulicHorsepower => baseUnitValue / 745.69988145d, + PowerUnit.JoulePerHour => baseUnitValue * 3600d, + PowerUnit.KilobritishThermalUnitPerHour => (baseUnitValue / 0.29307107017d) / 1e3d, + PowerUnit.KilojoulePerHour => (baseUnitValue * 3600d) / 1e3d, + PowerUnit.Kilowatt => (baseUnitValue) / 1e3d, + PowerUnit.MechanicalHorsepower => baseUnitValue / 745.69d, + PowerUnit.MegabritishThermalUnitPerHour => (baseUnitValue / 0.29307107017d) / 1e6d, + PowerUnit.MegajoulePerHour => (baseUnitValue * 3600d) / 1e6d, + PowerUnit.Megawatt => (baseUnitValue) / 1e6d, + PowerUnit.MetricHorsepower => baseUnitValue / 735.49875d, + PowerUnit.Microwatt => (baseUnitValue) / 1e-6d, + PowerUnit.MillijoulePerHour => (baseUnitValue * 3600d) / 1e-3d, + PowerUnit.Milliwatt => (baseUnitValue) / 1e-3d, + PowerUnit.Nanowatt => (baseUnitValue) / 1e-9d, + PowerUnit.Petawatt => (baseUnitValue) / 1e15d, + PowerUnit.Picowatt => (baseUnitValue) / 1e-12d, + PowerUnit.Terawatt => (baseUnitValue) / 1e12d, + PowerUnit.Watt => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerDensity.g.cs index 16ded66abd..da5a789354 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerDensity.g.cs @@ -580,139 +580,139 @@ public static PowerDensity From(double value, PowerDensityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerDensityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public PowerDensity ToUnit(PowerDensityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new PowerDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PowerDensityUnit.DecawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e1d, - PowerDensityUnit.DecawattPerCubicInch => (_value * 6.102374409473228e4) * 1e1d, - PowerDensityUnit.DecawattPerCubicMeter => (_value) * 1e1d, - PowerDensityUnit.DecawattPerLiter => (_value * 1.0e3) * 1e1d, - PowerDensityUnit.DeciwattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-1d, - PowerDensityUnit.DeciwattPerCubicInch => (_value * 6.102374409473228e4) * 1e-1d, - PowerDensityUnit.DeciwattPerCubicMeter => (_value) * 1e-1d, - PowerDensityUnit.DeciwattPerLiter => (_value * 1.0e3) * 1e-1d, - PowerDensityUnit.GigawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e9d, - PowerDensityUnit.GigawattPerCubicInch => (_value * 6.102374409473228e4) * 1e9d, - PowerDensityUnit.GigawattPerCubicMeter => (_value) * 1e9d, - PowerDensityUnit.GigawattPerLiter => (_value * 1.0e3) * 1e9d, - PowerDensityUnit.KilowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e3d, - PowerDensityUnit.KilowattPerCubicInch => (_value * 6.102374409473228e4) * 1e3d, - PowerDensityUnit.KilowattPerCubicMeter => (_value) * 1e3d, - PowerDensityUnit.KilowattPerLiter => (_value * 1.0e3) * 1e3d, - PowerDensityUnit.MegawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e6d, - PowerDensityUnit.MegawattPerCubicInch => (_value * 6.102374409473228e4) * 1e6d, - PowerDensityUnit.MegawattPerCubicMeter => (_value) * 1e6d, - PowerDensityUnit.MegawattPerLiter => (_value * 1.0e3) * 1e6d, - PowerDensityUnit.MicrowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-6d, - PowerDensityUnit.MicrowattPerCubicInch => (_value * 6.102374409473228e4) * 1e-6d, - PowerDensityUnit.MicrowattPerCubicMeter => (_value) * 1e-6d, - PowerDensityUnit.MicrowattPerLiter => (_value * 1.0e3) * 1e-6d, - PowerDensityUnit.MilliwattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-3d, - PowerDensityUnit.MilliwattPerCubicInch => (_value * 6.102374409473228e4) * 1e-3d, - PowerDensityUnit.MilliwattPerCubicMeter => (_value) * 1e-3d, - PowerDensityUnit.MilliwattPerLiter => (_value * 1.0e3) * 1e-3d, - PowerDensityUnit.NanowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-9d, - PowerDensityUnit.NanowattPerCubicInch => (_value * 6.102374409473228e4) * 1e-9d, - PowerDensityUnit.NanowattPerCubicMeter => (_value) * 1e-9d, - PowerDensityUnit.NanowattPerLiter => (_value * 1.0e3) * 1e-9d, - PowerDensityUnit.PicowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-12d, - PowerDensityUnit.PicowattPerCubicInch => (_value * 6.102374409473228e4) * 1e-12d, - PowerDensityUnit.PicowattPerCubicMeter => (_value) * 1e-12d, - PowerDensityUnit.PicowattPerLiter => (_value * 1.0e3) * 1e-12d, - PowerDensityUnit.TerawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e12d, - PowerDensityUnit.TerawattPerCubicInch => (_value * 6.102374409473228e4) * 1e12d, - PowerDensityUnit.TerawattPerCubicMeter => (_value) * 1e12d, - PowerDensityUnit.TerawattPerLiter => (_value * 1.0e3) * 1e12d, - PowerDensityUnit.WattPerCubicFoot => _value * 3.531466672148859e1, - PowerDensityUnit.WattPerCubicInch => _value * 6.102374409473228e4, - PowerDensityUnit.WattPerCubicMeter => _value, - PowerDensityUnit.WattPerLiter => _value * 1.0e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PowerDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PowerDensityUnit.DecawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e1d, - PowerDensityUnit.DecawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e1d, - PowerDensityUnit.DecawattPerCubicMeter => (baseUnitValue) / 1e1d, - PowerDensityUnit.DecawattPerLiter => (baseUnitValue / 1.0e3) / 1e1d, - PowerDensityUnit.DeciwattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-1d, - PowerDensityUnit.DeciwattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-1d, - PowerDensityUnit.DeciwattPerCubicMeter => (baseUnitValue) / 1e-1d, - PowerDensityUnit.DeciwattPerLiter => (baseUnitValue / 1.0e3) / 1e-1d, - PowerDensityUnit.GigawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e9d, - PowerDensityUnit.GigawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e9d, - PowerDensityUnit.GigawattPerCubicMeter => (baseUnitValue) / 1e9d, - PowerDensityUnit.GigawattPerLiter => (baseUnitValue / 1.0e3) / 1e9d, - PowerDensityUnit.KilowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e3d, - PowerDensityUnit.KilowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e3d, - PowerDensityUnit.KilowattPerCubicMeter => (baseUnitValue) / 1e3d, - PowerDensityUnit.KilowattPerLiter => (baseUnitValue / 1.0e3) / 1e3d, - PowerDensityUnit.MegawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e6d, - PowerDensityUnit.MegawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e6d, - PowerDensityUnit.MegawattPerCubicMeter => (baseUnitValue) / 1e6d, - PowerDensityUnit.MegawattPerLiter => (baseUnitValue / 1.0e3) / 1e6d, - PowerDensityUnit.MicrowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-6d, - PowerDensityUnit.MicrowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-6d, - PowerDensityUnit.MicrowattPerCubicMeter => (baseUnitValue) / 1e-6d, - PowerDensityUnit.MicrowattPerLiter => (baseUnitValue / 1.0e3) / 1e-6d, - PowerDensityUnit.MilliwattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-3d, - PowerDensityUnit.MilliwattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-3d, - PowerDensityUnit.MilliwattPerCubicMeter => (baseUnitValue) / 1e-3d, - PowerDensityUnit.MilliwattPerLiter => (baseUnitValue / 1.0e3) / 1e-3d, - PowerDensityUnit.NanowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-9d, - PowerDensityUnit.NanowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-9d, - PowerDensityUnit.NanowattPerCubicMeter => (baseUnitValue) / 1e-9d, - PowerDensityUnit.NanowattPerLiter => (baseUnitValue / 1.0e3) / 1e-9d, - PowerDensityUnit.PicowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-12d, - PowerDensityUnit.PicowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-12d, - PowerDensityUnit.PicowattPerCubicMeter => (baseUnitValue) / 1e-12d, - PowerDensityUnit.PicowattPerLiter => (baseUnitValue / 1.0e3) / 1e-12d, - PowerDensityUnit.TerawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e12d, - PowerDensityUnit.TerawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e12d, - PowerDensityUnit.TerawattPerCubicMeter => (baseUnitValue) / 1e12d, - PowerDensityUnit.TerawattPerLiter => (baseUnitValue / 1.0e3) / 1e12d, - PowerDensityUnit.WattPerCubicFoot => baseUnitValue / 3.531466672148859e1, - PowerDensityUnit.WattPerCubicInch => baseUnitValue / 6.102374409473228e4, - PowerDensityUnit.WattPerCubicMeter => baseUnitValue, - PowerDensityUnit.WattPerLiter => baseUnitValue / 1.0e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerDensityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public PowerDensity ToUnit(PowerDensityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new PowerDensity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PowerDensityUnit.DecawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e1d, + PowerDensityUnit.DecawattPerCubicInch => (_value * 6.102374409473228e4) * 1e1d, + PowerDensityUnit.DecawattPerCubicMeter => (_value) * 1e1d, + PowerDensityUnit.DecawattPerLiter => (_value * 1.0e3) * 1e1d, + PowerDensityUnit.DeciwattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-1d, + PowerDensityUnit.DeciwattPerCubicInch => (_value * 6.102374409473228e4) * 1e-1d, + PowerDensityUnit.DeciwattPerCubicMeter => (_value) * 1e-1d, + PowerDensityUnit.DeciwattPerLiter => (_value * 1.0e3) * 1e-1d, + PowerDensityUnit.GigawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e9d, + PowerDensityUnit.GigawattPerCubicInch => (_value * 6.102374409473228e4) * 1e9d, + PowerDensityUnit.GigawattPerCubicMeter => (_value) * 1e9d, + PowerDensityUnit.GigawattPerLiter => (_value * 1.0e3) * 1e9d, + PowerDensityUnit.KilowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e3d, + PowerDensityUnit.KilowattPerCubicInch => (_value * 6.102374409473228e4) * 1e3d, + PowerDensityUnit.KilowattPerCubicMeter => (_value) * 1e3d, + PowerDensityUnit.KilowattPerLiter => (_value * 1.0e3) * 1e3d, + PowerDensityUnit.MegawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e6d, + PowerDensityUnit.MegawattPerCubicInch => (_value * 6.102374409473228e4) * 1e6d, + PowerDensityUnit.MegawattPerCubicMeter => (_value) * 1e6d, + PowerDensityUnit.MegawattPerLiter => (_value * 1.0e3) * 1e6d, + PowerDensityUnit.MicrowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-6d, + PowerDensityUnit.MicrowattPerCubicInch => (_value * 6.102374409473228e4) * 1e-6d, + PowerDensityUnit.MicrowattPerCubicMeter => (_value) * 1e-6d, + PowerDensityUnit.MicrowattPerLiter => (_value * 1.0e3) * 1e-6d, + PowerDensityUnit.MilliwattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-3d, + PowerDensityUnit.MilliwattPerCubicInch => (_value * 6.102374409473228e4) * 1e-3d, + PowerDensityUnit.MilliwattPerCubicMeter => (_value) * 1e-3d, + PowerDensityUnit.MilliwattPerLiter => (_value * 1.0e3) * 1e-3d, + PowerDensityUnit.NanowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-9d, + PowerDensityUnit.NanowattPerCubicInch => (_value * 6.102374409473228e4) * 1e-9d, + PowerDensityUnit.NanowattPerCubicMeter => (_value) * 1e-9d, + PowerDensityUnit.NanowattPerLiter => (_value * 1.0e3) * 1e-9d, + PowerDensityUnit.PicowattPerCubicFoot => (_value * 3.531466672148859e1) * 1e-12d, + PowerDensityUnit.PicowattPerCubicInch => (_value * 6.102374409473228e4) * 1e-12d, + PowerDensityUnit.PicowattPerCubicMeter => (_value) * 1e-12d, + PowerDensityUnit.PicowattPerLiter => (_value * 1.0e3) * 1e-12d, + PowerDensityUnit.TerawattPerCubicFoot => (_value * 3.531466672148859e1) * 1e12d, + PowerDensityUnit.TerawattPerCubicInch => (_value * 6.102374409473228e4) * 1e12d, + PowerDensityUnit.TerawattPerCubicMeter => (_value) * 1e12d, + PowerDensityUnit.TerawattPerLiter => (_value * 1.0e3) * 1e12d, + PowerDensityUnit.WattPerCubicFoot => _value * 3.531466672148859e1, + PowerDensityUnit.WattPerCubicInch => _value * 6.102374409473228e4, + PowerDensityUnit.WattPerCubicMeter => _value, + PowerDensityUnit.WattPerLiter => _value * 1.0e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PowerDensityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PowerDensityUnit.DecawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e1d, + PowerDensityUnit.DecawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e1d, + PowerDensityUnit.DecawattPerCubicMeter => (baseUnitValue) / 1e1d, + PowerDensityUnit.DecawattPerLiter => (baseUnitValue / 1.0e3) / 1e1d, + PowerDensityUnit.DeciwattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-1d, + PowerDensityUnit.DeciwattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-1d, + PowerDensityUnit.DeciwattPerCubicMeter => (baseUnitValue) / 1e-1d, + PowerDensityUnit.DeciwattPerLiter => (baseUnitValue / 1.0e3) / 1e-1d, + PowerDensityUnit.GigawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e9d, + PowerDensityUnit.GigawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e9d, + PowerDensityUnit.GigawattPerCubicMeter => (baseUnitValue) / 1e9d, + PowerDensityUnit.GigawattPerLiter => (baseUnitValue / 1.0e3) / 1e9d, + PowerDensityUnit.KilowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e3d, + PowerDensityUnit.KilowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e3d, + PowerDensityUnit.KilowattPerCubicMeter => (baseUnitValue) / 1e3d, + PowerDensityUnit.KilowattPerLiter => (baseUnitValue / 1.0e3) / 1e3d, + PowerDensityUnit.MegawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e6d, + PowerDensityUnit.MegawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e6d, + PowerDensityUnit.MegawattPerCubicMeter => (baseUnitValue) / 1e6d, + PowerDensityUnit.MegawattPerLiter => (baseUnitValue / 1.0e3) / 1e6d, + PowerDensityUnit.MicrowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-6d, + PowerDensityUnit.MicrowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-6d, + PowerDensityUnit.MicrowattPerCubicMeter => (baseUnitValue) / 1e-6d, + PowerDensityUnit.MicrowattPerLiter => (baseUnitValue / 1.0e3) / 1e-6d, + PowerDensityUnit.MilliwattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-3d, + PowerDensityUnit.MilliwattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-3d, + PowerDensityUnit.MilliwattPerCubicMeter => (baseUnitValue) / 1e-3d, + PowerDensityUnit.MilliwattPerLiter => (baseUnitValue / 1.0e3) / 1e-3d, + PowerDensityUnit.NanowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-9d, + PowerDensityUnit.NanowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-9d, + PowerDensityUnit.NanowattPerCubicMeter => (baseUnitValue) / 1e-9d, + PowerDensityUnit.NanowattPerLiter => (baseUnitValue / 1.0e3) / 1e-9d, + PowerDensityUnit.PicowattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e-12d, + PowerDensityUnit.PicowattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e-12d, + PowerDensityUnit.PicowattPerCubicMeter => (baseUnitValue) / 1e-12d, + PowerDensityUnit.PicowattPerLiter => (baseUnitValue / 1.0e3) / 1e-12d, + PowerDensityUnit.TerawattPerCubicFoot => (baseUnitValue / 3.531466672148859e1) / 1e12d, + PowerDensityUnit.TerawattPerCubicInch => (baseUnitValue / 6.102374409473228e4) / 1e12d, + PowerDensityUnit.TerawattPerCubicMeter => (baseUnitValue) / 1e12d, + PowerDensityUnit.TerawattPerLiter => (baseUnitValue / 1.0e3) / 1e12d, + PowerDensityUnit.WattPerCubicFoot => baseUnitValue / 3.531466672148859e1, + PowerDensityUnit.WattPerCubicInch => baseUnitValue / 6.102374409473228e4, + PowerDensityUnit.WattPerCubicMeter => baseUnitValue, + PowerDensityUnit.WattPerLiter => baseUnitValue / 1.0e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerRatio.g.cs index 9f15e51918..3052127795 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PowerRatio.g.cs @@ -118,55 +118,55 @@ public static PowerRatio From(double value, PowerRatioUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerRatioUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public PowerRatio ToUnit(PowerRatioUnit unit) - { - var convertedValue = GetValueAs(unit); - return new PowerRatio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PowerRatioUnit.DecibelMilliwatt => _value - 30, - PowerRatioUnit.DecibelWatt => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PowerRatioUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PowerRatioUnit.DecibelMilliwatt => baseUnitValue + 30, - PowerRatioUnit.DecibelWatt => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PowerRatioUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public PowerRatio ToUnit(PowerRatioUnit unit) + { + var convertedValue = GetValueAs(unit); + return new PowerRatio(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PowerRatioUnit.DecibelMilliwatt => _value - 30, + PowerRatioUnit.DecibelWatt => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PowerRatioUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PowerRatioUnit.DecibelMilliwatt => baseUnitValue + 30, + PowerRatioUnit.DecibelWatt => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs index ce52b0c3f6..fe89149b52 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Pressure.g.cs @@ -613,145 +613,145 @@ public static Pressure From(double value, PressureUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Pressure ToUnit(PressureUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Pressure(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PressureUnit.Atmosphere => _value * 1.01325 * 1e5, - PressureUnit.Bar => _value * 1e5, - PressureUnit.Centibar => (_value * 1e5) * 1e-2d, - PressureUnit.Decapascal => (_value) * 1e1d, - PressureUnit.Decibar => (_value * 1e5) * 1e-1d, - PressureUnit.DynePerSquareCentimeter => _value * 1.0e-1, - PressureUnit.FootOfElevation => Math.Pow(1.0 - (_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0, - PressureUnit.FootOfHead => _value * 2989.0669, - PressureUnit.Gigapascal => (_value) * 1e9d, - PressureUnit.Hectopascal => (_value) * 1e2d, - PressureUnit.InchOfMercury => _value / 2.95299830714159e-4, - PressureUnit.InchOfWaterColumn => _value * 249.08890833333, - PressureUnit.Kilobar => (_value * 1e5) * 1e3d, - PressureUnit.KilogramForcePerSquareCentimeter => _value * 9.80665e4, - PressureUnit.KilogramForcePerSquareMeter => _value * 9.80665019960652, - PressureUnit.KilogramForcePerSquareMillimeter => _value * 9.80665e6, - PressureUnit.KilonewtonPerSquareCentimeter => (_value * 1e4) * 1e3d, - PressureUnit.KilonewtonPerSquareMeter => (_value) * 1e3d, - PressureUnit.KilonewtonPerSquareMillimeter => (_value * 1e6) * 1e3d, - PressureUnit.Kilopascal => (_value) * 1e3d, - PressureUnit.KilopoundForcePerSquareFoot => (_value * 4.788025898033584e1) * 1e3d, - PressureUnit.KilopoundForcePerSquareInch => (_value * 6.894757293168361e3) * 1e3d, - PressureUnit.KilopoundForcePerSquareMil => (_value * 6.894757293168361e9) * 1e3d, - PressureUnit.Megabar => (_value * 1e5) * 1e6d, - PressureUnit.MeganewtonPerSquareMeter => (_value) * 1e6d, - PressureUnit.Megapascal => (_value) * 1e6d, - PressureUnit.MeterOfElevation => Math.Pow(1.0 - (_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0, - PressureUnit.MeterOfHead => _value * 9804.139432, - PressureUnit.Microbar => (_value * 1e5) * 1e-6d, - PressureUnit.Micropascal => (_value) * 1e-6d, - PressureUnit.Millibar => (_value * 1e5) * 1e-3d, - PressureUnit.MillimeterOfMercury => _value / 7.50061561302643e-3, - PressureUnit.MillimeterOfWaterColumn => _value * 9.806650000000272e0, - PressureUnit.Millipascal => (_value) * 1e-3d, - PressureUnit.NewtonPerSquareCentimeter => _value * 1e4, - PressureUnit.NewtonPerSquareMeter => _value, - PressureUnit.NewtonPerSquareMillimeter => _value * 1e6, - PressureUnit.Pascal => _value, - PressureUnit.PoundForcePerSquareFoot => _value * 4.788025898033584e1, - PressureUnit.PoundForcePerSquareInch => _value * 6.894757293168361e3, - PressureUnit.PoundForcePerSquareMil => _value * 6.894757293168361e9, - PressureUnit.PoundPerInchSecondSquared => _value * 1.785796732283465e1, - PressureUnit.TechnicalAtmosphere => _value * 9.80680592331 * 1e4, - PressureUnit.TonneForcePerSquareCentimeter => _value * 9.80665e7, - PressureUnit.TonneForcePerSquareMeter => _value * 9.80665e3, - PressureUnit.TonneForcePerSquareMillimeter => _value * 9.80665e9, - PressureUnit.Torr => _value * 1.3332266752 * 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PressureUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PressureUnit.Atmosphere => baseUnitValue / (1.01325 * 1e5), - PressureUnit.Bar => baseUnitValue / 1e5, - PressureUnit.Centibar => (baseUnitValue / 1e5) / 1e-2d, - PressureUnit.Decapascal => (baseUnitValue) / 1e1d, - PressureUnit.Decibar => (baseUnitValue / 1e5) / 1e-1d, - PressureUnit.DynePerSquareCentimeter => baseUnitValue / 1.0e-1, - PressureUnit.FootOfElevation => (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 145366.45, - PressureUnit.FootOfHead => baseUnitValue * 0.000334552565551, - PressureUnit.Gigapascal => (baseUnitValue) / 1e9d, - PressureUnit.Hectopascal => (baseUnitValue) / 1e2d, - PressureUnit.InchOfMercury => baseUnitValue * 2.95299830714159e-4, - PressureUnit.InchOfWaterColumn => baseUnitValue / 249.08890833333, - PressureUnit.Kilobar => (baseUnitValue / 1e5) / 1e3d, - PressureUnit.KilogramForcePerSquareCentimeter => baseUnitValue / 9.80665e4, - PressureUnit.KilogramForcePerSquareMeter => baseUnitValue * 0.101971619222242, - PressureUnit.KilogramForcePerSquareMillimeter => baseUnitValue / 9.80665e6, - PressureUnit.KilonewtonPerSquareCentimeter => (baseUnitValue / 1e4) / 1e3d, - PressureUnit.KilonewtonPerSquareMeter => (baseUnitValue) / 1e3d, - PressureUnit.KilonewtonPerSquareMillimeter => (baseUnitValue / 1e6) / 1e3d, - PressureUnit.Kilopascal => (baseUnitValue) / 1e3d, - PressureUnit.KilopoundForcePerSquareFoot => (baseUnitValue / 4.788025898033584e1) / 1e3d, - PressureUnit.KilopoundForcePerSquareInch => (baseUnitValue / 6.894757293168361e3) / 1e3d, - PressureUnit.KilopoundForcePerSquareMil => (baseUnitValue / 6.894757293168361e9) / 1e3d, - PressureUnit.Megabar => (baseUnitValue / 1e5) / 1e6d, - PressureUnit.MeganewtonPerSquareMeter => (baseUnitValue) / 1e6d, - PressureUnit.Megapascal => (baseUnitValue) / 1e6d, - PressureUnit.MeterOfElevation => (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 44307.69396, - PressureUnit.MeterOfHead => baseUnitValue * 0.0001019977334, - PressureUnit.Microbar => (baseUnitValue / 1e5) / 1e-6d, - PressureUnit.Micropascal => (baseUnitValue) / 1e-6d, - PressureUnit.Millibar => (baseUnitValue / 1e5) / 1e-3d, - PressureUnit.MillimeterOfMercury => baseUnitValue * 7.50061561302643e-3, - PressureUnit.MillimeterOfWaterColumn => baseUnitValue / 9.806650000000272e0, - PressureUnit.Millipascal => (baseUnitValue) / 1e-3d, - PressureUnit.NewtonPerSquareCentimeter => baseUnitValue / 1e4, - PressureUnit.NewtonPerSquareMeter => baseUnitValue, - PressureUnit.NewtonPerSquareMillimeter => baseUnitValue / 1e6, - PressureUnit.Pascal => baseUnitValue, - PressureUnit.PoundForcePerSquareFoot => baseUnitValue / 4.788025898033584e1, - PressureUnit.PoundForcePerSquareInch => baseUnitValue / 6.894757293168361e3, - PressureUnit.PoundForcePerSquareMil => baseUnitValue / 6.894757293168361e9, - PressureUnit.PoundPerInchSecondSquared => baseUnitValue / 1.785796732283465e1, - PressureUnit.TechnicalAtmosphere => baseUnitValue / (9.80680592331 * 1e4), - PressureUnit.TonneForcePerSquareCentimeter => baseUnitValue / 9.80665e7, - PressureUnit.TonneForcePerSquareMeter => baseUnitValue / 9.80665e3, - PressureUnit.TonneForcePerSquareMillimeter => baseUnitValue / 9.80665e9, - PressureUnit.Torr => baseUnitValue / (1.3332266752 * 1e2), - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PressureUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Pressure ToUnit(PressureUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Pressure(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PressureUnit.Atmosphere => _value * 1.01325 * 1e5, + PressureUnit.Bar => _value * 1e5, + PressureUnit.Centibar => (_value * 1e5) * 1e-2d, + PressureUnit.Decapascal => (_value) * 1e1d, + PressureUnit.Decibar => (_value * 1e5) * 1e-1d, + PressureUnit.DynePerSquareCentimeter => _value * 1.0e-1, + PressureUnit.FootOfElevation => Math.Pow(1.0 - (_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0, + PressureUnit.FootOfHead => _value * 2989.0669, + PressureUnit.Gigapascal => (_value) * 1e9d, + PressureUnit.Hectopascal => (_value) * 1e2d, + PressureUnit.InchOfMercury => _value / 2.95299830714159e-4, + PressureUnit.InchOfWaterColumn => _value * 249.08890833333, + PressureUnit.Kilobar => (_value * 1e5) * 1e3d, + PressureUnit.KilogramForcePerSquareCentimeter => _value * 9.80665e4, + PressureUnit.KilogramForcePerSquareMeter => _value * 9.80665019960652, + PressureUnit.KilogramForcePerSquareMillimeter => _value * 9.80665e6, + PressureUnit.KilonewtonPerSquareCentimeter => (_value * 1e4) * 1e3d, + PressureUnit.KilonewtonPerSquareMeter => (_value) * 1e3d, + PressureUnit.KilonewtonPerSquareMillimeter => (_value * 1e6) * 1e3d, + PressureUnit.Kilopascal => (_value) * 1e3d, + PressureUnit.KilopoundForcePerSquareFoot => (_value * 4.788025898033584e1) * 1e3d, + PressureUnit.KilopoundForcePerSquareInch => (_value * 6.894757293168361e3) * 1e3d, + PressureUnit.KilopoundForcePerSquareMil => (_value * 6.894757293168361e9) * 1e3d, + PressureUnit.Megabar => (_value * 1e5) * 1e6d, + PressureUnit.MeganewtonPerSquareMeter => (_value) * 1e6d, + PressureUnit.Megapascal => (_value) * 1e6d, + PressureUnit.MeterOfElevation => Math.Pow(1.0 - (_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0, + PressureUnit.MeterOfHead => _value * 9804.139432, + PressureUnit.Microbar => (_value * 1e5) * 1e-6d, + PressureUnit.Micropascal => (_value) * 1e-6d, + PressureUnit.Millibar => (_value * 1e5) * 1e-3d, + PressureUnit.MillimeterOfMercury => _value / 7.50061561302643e-3, + PressureUnit.MillimeterOfWaterColumn => _value * 9.806650000000272e0, + PressureUnit.Millipascal => (_value) * 1e-3d, + PressureUnit.NewtonPerSquareCentimeter => _value * 1e4, + PressureUnit.NewtonPerSquareMeter => _value, + PressureUnit.NewtonPerSquareMillimeter => _value * 1e6, + PressureUnit.Pascal => _value, + PressureUnit.PoundForcePerSquareFoot => _value * 4.788025898033584e1, + PressureUnit.PoundForcePerSquareInch => _value * 6.894757293168361e3, + PressureUnit.PoundForcePerSquareMil => _value * 6.894757293168361e9, + PressureUnit.PoundPerInchSecondSquared => _value * 1.785796732283465e1, + PressureUnit.TechnicalAtmosphere => _value * 9.80680592331 * 1e4, + PressureUnit.TonneForcePerSquareCentimeter => _value * 9.80665e7, + PressureUnit.TonneForcePerSquareMeter => _value * 9.80665e3, + PressureUnit.TonneForcePerSquareMillimeter => _value * 9.80665e9, + PressureUnit.Torr => _value * 1.3332266752 * 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PressureUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PressureUnit.Atmosphere => baseUnitValue / (1.01325 * 1e5), + PressureUnit.Bar => baseUnitValue / 1e5, + PressureUnit.Centibar => (baseUnitValue / 1e5) / 1e-2d, + PressureUnit.Decapascal => (baseUnitValue) / 1e1d, + PressureUnit.Decibar => (baseUnitValue / 1e5) / 1e-1d, + PressureUnit.DynePerSquareCentimeter => baseUnitValue / 1.0e-1, + PressureUnit.FootOfElevation => (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 145366.45, + PressureUnit.FootOfHead => baseUnitValue * 0.000334552565551, + PressureUnit.Gigapascal => (baseUnitValue) / 1e9d, + PressureUnit.Hectopascal => (baseUnitValue) / 1e2d, + PressureUnit.InchOfMercury => baseUnitValue * 2.95299830714159e-4, + PressureUnit.InchOfWaterColumn => baseUnitValue / 249.08890833333, + PressureUnit.Kilobar => (baseUnitValue / 1e5) / 1e3d, + PressureUnit.KilogramForcePerSquareCentimeter => baseUnitValue / 9.80665e4, + PressureUnit.KilogramForcePerSquareMeter => baseUnitValue * 0.101971619222242, + PressureUnit.KilogramForcePerSquareMillimeter => baseUnitValue / 9.80665e6, + PressureUnit.KilonewtonPerSquareCentimeter => (baseUnitValue / 1e4) / 1e3d, + PressureUnit.KilonewtonPerSquareMeter => (baseUnitValue) / 1e3d, + PressureUnit.KilonewtonPerSquareMillimeter => (baseUnitValue / 1e6) / 1e3d, + PressureUnit.Kilopascal => (baseUnitValue) / 1e3d, + PressureUnit.KilopoundForcePerSquareFoot => (baseUnitValue / 4.788025898033584e1) / 1e3d, + PressureUnit.KilopoundForcePerSquareInch => (baseUnitValue / 6.894757293168361e3) / 1e3d, + PressureUnit.KilopoundForcePerSquareMil => (baseUnitValue / 6.894757293168361e9) / 1e3d, + PressureUnit.Megabar => (baseUnitValue / 1e5) / 1e6d, + PressureUnit.MeganewtonPerSquareMeter => (baseUnitValue) / 1e6d, + PressureUnit.Megapascal => (baseUnitValue) / 1e6d, + PressureUnit.MeterOfElevation => (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 44307.69396, + PressureUnit.MeterOfHead => baseUnitValue * 0.0001019977334, + PressureUnit.Microbar => (baseUnitValue / 1e5) / 1e-6d, + PressureUnit.Micropascal => (baseUnitValue) / 1e-6d, + PressureUnit.Millibar => (baseUnitValue / 1e5) / 1e-3d, + PressureUnit.MillimeterOfMercury => baseUnitValue * 7.50061561302643e-3, + PressureUnit.MillimeterOfWaterColumn => baseUnitValue / 9.806650000000272e0, + PressureUnit.Millipascal => (baseUnitValue) / 1e-3d, + PressureUnit.NewtonPerSquareCentimeter => baseUnitValue / 1e4, + PressureUnit.NewtonPerSquareMeter => baseUnitValue, + PressureUnit.NewtonPerSquareMillimeter => baseUnitValue / 1e6, + PressureUnit.Pascal => baseUnitValue, + PressureUnit.PoundForcePerSquareFoot => baseUnitValue / 4.788025898033584e1, + PressureUnit.PoundForcePerSquareInch => baseUnitValue / 6.894757293168361e3, + PressureUnit.PoundForcePerSquareMil => baseUnitValue / 6.894757293168361e9, + PressureUnit.PoundPerInchSecondSquared => baseUnitValue / 1.785796732283465e1, + PressureUnit.TechnicalAtmosphere => baseUnitValue / (9.80680592331 * 1e4), + PressureUnit.TonneForcePerSquareCentimeter => baseUnitValue / 9.80665e7, + PressureUnit.TonneForcePerSquareMeter => baseUnitValue / 9.80665e3, + PressureUnit.TonneForcePerSquareMillimeter => baseUnitValue / 9.80665e9, + PressureUnit.Torr => baseUnitValue / (1.3332266752 * 1e2), + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PressureChangeRate.g.cs index 90bc5ecdd7..2baa14fb03 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -250,79 +250,79 @@ public static PressureChangeRate From(double value, PressureChangeRateUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureChangeRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public PressureChangeRate ToUnit(PressureChangeRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new PressureChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - PressureChangeRateUnit.AtmospherePerSecond => _value * 1.01325 * 1e5, - PressureChangeRateUnit.KilopascalPerMinute => (_value / 60) * 1e3d, - PressureChangeRateUnit.KilopascalPerSecond => (_value) * 1e3d, - PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute => (_value * 6.894757293168361e3 / 60) * 1e3d, - PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond => (_value * 6.894757293168361e3) * 1e3d, - PressureChangeRateUnit.MegapascalPerMinute => (_value / 60) * 1e6d, - PressureChangeRateUnit.MegapascalPerSecond => (_value) * 1e6d, - PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute => (_value * 6.894757293168361e3 / 60) * 1e6d, - PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond => (_value * 6.894757293168361e3) * 1e6d, - PressureChangeRateUnit.MillimeterOfMercuryPerSecond => _value * 133.322, - PressureChangeRateUnit.PascalPerMinute => _value / 60, - PressureChangeRateUnit.PascalPerSecond => _value, - PressureChangeRateUnit.PoundForcePerSquareInchPerMinute => _value * 6.894757293168361e3 / 60, - PressureChangeRateUnit.PoundForcePerSquareInchPerSecond => _value * 6.894757293168361e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(PressureChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - PressureChangeRateUnit.AtmospherePerSecond => baseUnitValue / (1.01325 * 1e5), - PressureChangeRateUnit.KilopascalPerMinute => (baseUnitValue * 60) / 1e3d, - PressureChangeRateUnit.KilopascalPerSecond => (baseUnitValue) / 1e3d, - PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute => (baseUnitValue / 6.894757293168361e3 * 60) / 1e3d, - PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond => (baseUnitValue / 6.894757293168361e3) / 1e3d, - PressureChangeRateUnit.MegapascalPerMinute => (baseUnitValue * 60) / 1e6d, - PressureChangeRateUnit.MegapascalPerSecond => (baseUnitValue) / 1e6d, - PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute => (baseUnitValue / 6.894757293168361e3 * 60) / 1e6d, - PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond => (baseUnitValue / 6.894757293168361e3) / 1e6d, - PressureChangeRateUnit.MillimeterOfMercuryPerSecond => baseUnitValue / 133.322, - PressureChangeRateUnit.PascalPerMinute => baseUnitValue * 60, - PressureChangeRateUnit.PascalPerSecond => baseUnitValue, - PressureChangeRateUnit.PoundForcePerSquareInchPerMinute => baseUnitValue / 6.894757293168361e3 * 60, - PressureChangeRateUnit.PoundForcePerSquareInchPerSecond => baseUnitValue / 6.894757293168361e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(PressureChangeRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public PressureChangeRate ToUnit(PressureChangeRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new PressureChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + PressureChangeRateUnit.AtmospherePerSecond => _value * 1.01325 * 1e5, + PressureChangeRateUnit.KilopascalPerMinute => (_value / 60) * 1e3d, + PressureChangeRateUnit.KilopascalPerSecond => (_value) * 1e3d, + PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute => (_value * 6.894757293168361e3 / 60) * 1e3d, + PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond => (_value * 6.894757293168361e3) * 1e3d, + PressureChangeRateUnit.MegapascalPerMinute => (_value / 60) * 1e6d, + PressureChangeRateUnit.MegapascalPerSecond => (_value) * 1e6d, + PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute => (_value * 6.894757293168361e3 / 60) * 1e6d, + PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond => (_value * 6.894757293168361e3) * 1e6d, + PressureChangeRateUnit.MillimeterOfMercuryPerSecond => _value * 133.322, + PressureChangeRateUnit.PascalPerMinute => _value / 60, + PressureChangeRateUnit.PascalPerSecond => _value, + PressureChangeRateUnit.PoundForcePerSquareInchPerMinute => _value * 6.894757293168361e3 / 60, + PressureChangeRateUnit.PoundForcePerSquareInchPerSecond => _value * 6.894757293168361e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(PressureChangeRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + PressureChangeRateUnit.AtmospherePerSecond => baseUnitValue / (1.01325 * 1e5), + PressureChangeRateUnit.KilopascalPerMinute => (baseUnitValue * 60) / 1e3d, + PressureChangeRateUnit.KilopascalPerSecond => (baseUnitValue) / 1e3d, + PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute => (baseUnitValue / 6.894757293168361e3 * 60) / 1e3d, + PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond => (baseUnitValue / 6.894757293168361e3) / 1e3d, + PressureChangeRateUnit.MegapascalPerMinute => (baseUnitValue * 60) / 1e6d, + PressureChangeRateUnit.MegapascalPerSecond => (baseUnitValue) / 1e6d, + PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute => (baseUnitValue / 6.894757293168361e3 * 60) / 1e6d, + PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond => (baseUnitValue / 6.894757293168361e3) / 1e6d, + PressureChangeRateUnit.MillimeterOfMercuryPerSecond => baseUnitValue / 133.322, + PressureChangeRateUnit.PascalPerMinute => baseUnitValue * 60, + PressureChangeRateUnit.PascalPerSecond => baseUnitValue, + PressureChangeRateUnit.PoundForcePerSquareInchPerMinute => baseUnitValue / 6.894757293168361e3 * 60, + PressureChangeRateUnit.PoundForcePerSquareInchPerSecond => baseUnitValue / 6.894757293168361e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Ratio.g.cs index 0ca04c3de2..84ee01e6ec 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Ratio.g.cs @@ -162,63 +162,63 @@ public static Ratio From(double value, RatioUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Ratio ToUnit(RatioUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Ratio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RatioUnit.DecimalFraction => _value, - RatioUnit.PartPerBillion => _value / 1e9, - RatioUnit.PartPerMillion => _value / 1e6, - RatioUnit.PartPerThousand => _value / 1e3, - RatioUnit.PartPerTrillion => _value / 1e12, - RatioUnit.Percent => _value / 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RatioUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RatioUnit.DecimalFraction => baseUnitValue, - RatioUnit.PartPerBillion => baseUnitValue * 1e9, - RatioUnit.PartPerMillion => baseUnitValue * 1e6, - RatioUnit.PartPerThousand => baseUnitValue * 1e3, - RatioUnit.PartPerTrillion => baseUnitValue * 1e12, - RatioUnit.Percent => baseUnitValue * 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RatioUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Ratio ToUnit(RatioUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Ratio(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RatioUnit.DecimalFraction => _value, + RatioUnit.PartPerBillion => _value / 1e9, + RatioUnit.PartPerMillion => _value / 1e6, + RatioUnit.PartPerThousand => _value / 1e3, + RatioUnit.PartPerTrillion => _value / 1e12, + RatioUnit.Percent => _value / 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RatioUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RatioUnit.DecimalFraction => baseUnitValue, + RatioUnit.PartPerBillion => baseUnitValue * 1e9, + RatioUnit.PartPerMillion => baseUnitValue * 1e6, + RatioUnit.PartPerThousand => baseUnitValue * 1e3, + RatioUnit.PartPerTrillion => baseUnitValue * 1e12, + RatioUnit.Percent => baseUnitValue * 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RatioChangeRate.g.cs index 8039f4caf0..7140dc12ee 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -118,55 +118,55 @@ public static RatioChangeRate From(double value, RatioChangeRateUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioChangeRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public RatioChangeRate ToUnit(RatioChangeRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new RatioChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RatioChangeRateUnit.DecimalFractionPerSecond => _value, - RatioChangeRateUnit.PercentPerSecond => _value / 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RatioChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RatioChangeRateUnit.DecimalFractionPerSecond => baseUnitValue, - RatioChangeRateUnit.PercentPerSecond => baseUnitValue * 1e2, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RatioChangeRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public RatioChangeRate ToUnit(RatioChangeRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new RatioChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RatioChangeRateUnit.DecimalFractionPerSecond => _value, + RatioChangeRateUnit.PercentPerSecond => _value / 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RatioChangeRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RatioChangeRateUnit.DecimalFractionPerSecond => baseUnitValue, + RatioChangeRateUnit.PercentPerSecond => baseUnitValue * 1e2, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactiveEnergy.g.cs index a82821527a..08d58258a0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactiveEnergy.g.cs @@ -129,57 +129,57 @@ public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactiveEnergyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ReactiveEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ReactiveEnergyUnit.KilovoltampereReactiveHour => (_value) * 1e3d, - ReactiveEnergyUnit.MegavoltampereReactiveHour => (_value) * 1e6d, - ReactiveEnergyUnit.VoltampereReactiveHour => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ReactiveEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ReactiveEnergyUnit.KilovoltampereReactiveHour => (baseUnitValue) / 1e3d, - ReactiveEnergyUnit.MegavoltampereReactiveHour => (baseUnitValue) / 1e6d, - ReactiveEnergyUnit.VoltampereReactiveHour => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReactiveEnergyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ReactiveEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ReactiveEnergyUnit.KilovoltampereReactiveHour => (_value) * 1e3d, + ReactiveEnergyUnit.MegavoltampereReactiveHour => (_value) * 1e6d, + ReactiveEnergyUnit.VoltampereReactiveHour => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ReactiveEnergyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ReactiveEnergyUnit.KilovoltampereReactiveHour => (baseUnitValue) / 1e3d, + ReactiveEnergyUnit.MegavoltampereReactiveHour => (baseUnitValue) / 1e6d, + ReactiveEnergyUnit.VoltampereReactiveHour => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactivePower.g.cs index 7163ffd1fa..048cc6f15e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactivePower.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReactivePower.g.cs @@ -140,59 +140,59 @@ public static ReactivePower From(double value, ReactivePowerUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactivePowerUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ReactivePower ToUnit(ReactivePowerUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ReactivePower(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ReactivePowerUnit.GigavoltampereReactive => (_value) * 1e9d, - ReactivePowerUnit.KilovoltampereReactive => (_value) * 1e3d, - ReactivePowerUnit.MegavoltampereReactive => (_value) * 1e6d, - ReactivePowerUnit.VoltampereReactive => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ReactivePowerUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ReactivePowerUnit.GigavoltampereReactive => (baseUnitValue) / 1e9d, - ReactivePowerUnit.KilovoltampereReactive => (baseUnitValue) / 1e3d, - ReactivePowerUnit.MegavoltampereReactive => (baseUnitValue) / 1e6d, - ReactivePowerUnit.VoltampereReactive => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReactivePowerUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ReactivePower ToUnit(ReactivePowerUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ReactivePower(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ReactivePowerUnit.GigavoltampereReactive => (_value) * 1e9d, + ReactivePowerUnit.KilovoltampereReactive => (_value) * 1e3d, + ReactivePowerUnit.MegavoltampereReactive => (_value) * 1e6d, + ReactivePowerUnit.VoltampereReactive => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ReactivePowerUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ReactivePowerUnit.GigavoltampereReactive => (baseUnitValue) / 1e9d, + ReactivePowerUnit.KilovoltampereReactive => (baseUnitValue) / 1e3d, + ReactivePowerUnit.MegavoltampereReactive => (baseUnitValue) / 1e6d, + ReactivePowerUnit.VoltampereReactive => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalArea.g.cs index 99e3228520..ce76b727e3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -220,73 +220,73 @@ public static ReciprocalArea From(double value, ReciprocalAreaUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReciprocalAreaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ReciprocalArea ToUnit(ReciprocalAreaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ReciprocalArea(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ReciprocalAreaUnit.InverseSquareCentimeter => _value / 1e-4, - ReciprocalAreaUnit.InverseSquareDecimeter => _value / 1e-2, - ReciprocalAreaUnit.InverseSquareFoot => _value / 0.092903, - ReciprocalAreaUnit.InverseSquareInch => _value / 0.00064516, - ReciprocalAreaUnit.InverseSquareKilometer => _value / 1e6, - ReciprocalAreaUnit.InverseSquareMeter => _value, - ReciprocalAreaUnit.InverseSquareMicrometer => _value / 1e-12, - ReciprocalAreaUnit.InverseSquareMile => _value / 2.59e6, - ReciprocalAreaUnit.InverseSquareMillimeter => _value / 1e-6, - ReciprocalAreaUnit.InverseSquareYard => _value / 0.836127, - ReciprocalAreaUnit.InverseUsSurveySquareFoot => _value / 0.09290341161, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ReciprocalAreaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ReciprocalAreaUnit.InverseSquareCentimeter => baseUnitValue * 1e-4, - ReciprocalAreaUnit.InverseSquareDecimeter => baseUnitValue * 1e-2, - ReciprocalAreaUnit.InverseSquareFoot => baseUnitValue * 0.092903, - ReciprocalAreaUnit.InverseSquareInch => baseUnitValue * 0.00064516, - ReciprocalAreaUnit.InverseSquareKilometer => baseUnitValue * 1e6, - ReciprocalAreaUnit.InverseSquareMeter => baseUnitValue, - ReciprocalAreaUnit.InverseSquareMicrometer => baseUnitValue * 1e-12, - ReciprocalAreaUnit.InverseSquareMile => baseUnitValue * 2.59e6, - ReciprocalAreaUnit.InverseSquareMillimeter => baseUnitValue * 1e-6, - ReciprocalAreaUnit.InverseSquareYard => baseUnitValue * 0.836127, - ReciprocalAreaUnit.InverseUsSurveySquareFoot => baseUnitValue * 0.09290341161, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReciprocalAreaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ReciprocalArea ToUnit(ReciprocalAreaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ReciprocalArea(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ReciprocalAreaUnit.InverseSquareCentimeter => _value / 1e-4, + ReciprocalAreaUnit.InverseSquareDecimeter => _value / 1e-2, + ReciprocalAreaUnit.InverseSquareFoot => _value / 0.092903, + ReciprocalAreaUnit.InverseSquareInch => _value / 0.00064516, + ReciprocalAreaUnit.InverseSquareKilometer => _value / 1e6, + ReciprocalAreaUnit.InverseSquareMeter => _value, + ReciprocalAreaUnit.InverseSquareMicrometer => _value / 1e-12, + ReciprocalAreaUnit.InverseSquareMile => _value / 2.59e6, + ReciprocalAreaUnit.InverseSquareMillimeter => _value / 1e-6, + ReciprocalAreaUnit.InverseSquareYard => _value / 0.836127, + ReciprocalAreaUnit.InverseUsSurveySquareFoot => _value / 0.09290341161, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ReciprocalAreaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ReciprocalAreaUnit.InverseSquareCentimeter => baseUnitValue * 1e-4, + ReciprocalAreaUnit.InverseSquareDecimeter => baseUnitValue * 1e-2, + ReciprocalAreaUnit.InverseSquareFoot => baseUnitValue * 0.092903, + ReciprocalAreaUnit.InverseSquareInch => baseUnitValue * 0.00064516, + ReciprocalAreaUnit.InverseSquareKilometer => baseUnitValue * 1e6, + ReciprocalAreaUnit.InverseSquareMeter => baseUnitValue, + ReciprocalAreaUnit.InverseSquareMicrometer => baseUnitValue * 1e-12, + ReciprocalAreaUnit.InverseSquareMile => baseUnitValue * 2.59e6, + ReciprocalAreaUnit.InverseSquareMillimeter => baseUnitValue * 1e-6, + ReciprocalAreaUnit.InverseSquareYard => baseUnitValue * 0.836127, + ReciprocalAreaUnit.InverseUsSurveySquareFoot => baseUnitValue * 0.09290341161, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalLength.g.cs index 9393359c5c..adf21b7898 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -209,71 +209,71 @@ public static ReciprocalLength From(double value, ReciprocalLengthUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReciprocalLengthUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ReciprocalLength ToUnit(ReciprocalLengthUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ReciprocalLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ReciprocalLengthUnit.InverseCentimeter => _value * 1e2, - ReciprocalLengthUnit.InverseFoot => _value / 0.3048, - ReciprocalLengthUnit.InverseInch => _value / 2.54e-2, - ReciprocalLengthUnit.InverseMeter => _value, - ReciprocalLengthUnit.InverseMicroinch => _value / 2.54e-8, - ReciprocalLengthUnit.InverseMil => _value / 2.54e-5, - ReciprocalLengthUnit.InverseMile => _value / 1609.34, - ReciprocalLengthUnit.InverseMillimeter => _value * 1e3, - ReciprocalLengthUnit.InverseUsSurveyFoot => _value * 3937 / 1200, - ReciprocalLengthUnit.InverseYard => _value / 0.9144, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ReciprocalLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ReciprocalLengthUnit.InverseCentimeter => baseUnitValue / 1e2, - ReciprocalLengthUnit.InverseFoot => baseUnitValue * 0.3048, - ReciprocalLengthUnit.InverseInch => baseUnitValue * 2.54e-2, - ReciprocalLengthUnit.InverseMeter => baseUnitValue, - ReciprocalLengthUnit.InverseMicroinch => baseUnitValue * 2.54e-8, - ReciprocalLengthUnit.InverseMil => baseUnitValue * 2.54e-5, - ReciprocalLengthUnit.InverseMile => baseUnitValue * 1609.34, - ReciprocalLengthUnit.InverseMillimeter => baseUnitValue / 1e3, - ReciprocalLengthUnit.InverseUsSurveyFoot => baseUnitValue * 1200 / 3937, - ReciprocalLengthUnit.InverseYard => baseUnitValue * 0.9144, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ReciprocalLengthUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ReciprocalLength ToUnit(ReciprocalLengthUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ReciprocalLength(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ReciprocalLengthUnit.InverseCentimeter => _value * 1e2, + ReciprocalLengthUnit.InverseFoot => _value / 0.3048, + ReciprocalLengthUnit.InverseInch => _value / 2.54e-2, + ReciprocalLengthUnit.InverseMeter => _value, + ReciprocalLengthUnit.InverseMicroinch => _value / 2.54e-8, + ReciprocalLengthUnit.InverseMil => _value / 2.54e-5, + ReciprocalLengthUnit.InverseMile => _value / 1609.34, + ReciprocalLengthUnit.InverseMillimeter => _value * 1e3, + ReciprocalLengthUnit.InverseUsSurveyFoot => _value * 3937 / 1200, + ReciprocalLengthUnit.InverseYard => _value / 0.9144, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ReciprocalLengthUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ReciprocalLengthUnit.InverseCentimeter => baseUnitValue / 1e2, + ReciprocalLengthUnit.InverseFoot => baseUnitValue * 0.3048, + ReciprocalLengthUnit.InverseInch => baseUnitValue * 2.54e-2, + ReciprocalLengthUnit.InverseMeter => baseUnitValue, + ReciprocalLengthUnit.InverseMicroinch => baseUnitValue * 2.54e-8, + ReciprocalLengthUnit.InverseMil => baseUnitValue * 2.54e-5, + ReciprocalLengthUnit.InverseMile => baseUnitValue * 1609.34, + ReciprocalLengthUnit.InverseMillimeter => baseUnitValue / 1e3, + ReciprocalLengthUnit.InverseUsSurveyFoot => baseUnitValue * 1200 / 3937, + ReciprocalLengthUnit.InverseYard => baseUnitValue * 0.9144, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RelativeHumidity.g.cs index d0215b1c6f..b029e6a377 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -107,53 +107,53 @@ public static RelativeHumidity From(double value, RelativeHumidityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RelativeHumidityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public RelativeHumidity ToUnit(RelativeHumidityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new RelativeHumidity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RelativeHumidityUnit.Percent => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RelativeHumidityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RelativeHumidityUnit.Percent => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RelativeHumidityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public RelativeHumidity ToUnit(RelativeHumidityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new RelativeHumidity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RelativeHumidityUnit.Percent => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RelativeHumidityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RelativeHumidityUnit.Percent => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalAcceleration.g.cs index 33cb6211cd..b8be193d41 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -140,59 +140,59 @@ public static RotationalAcceleration From(double value, RotationalAccelerationUn #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalAccelerationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new RotationalAcceleration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RotationalAccelerationUnit.DegreePerSecondSquared => (3.1415926535897931 / 180) * _value, - RotationalAccelerationUnit.RadianPerSecondSquared => _value, - RotationalAccelerationUnit.RevolutionPerMinutePerSecond => ((2 * 3.1415926535897931) / 60) * _value, - RotationalAccelerationUnit.RevolutionPerSecondSquared => (2 * 3.1415926535897931) * _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RotationalAccelerationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RotationalAccelerationUnit.DegreePerSecondSquared => (180 / 3.1415926535897931) * baseUnitValue, - RotationalAccelerationUnit.RadianPerSecondSquared => baseUnitValue, - RotationalAccelerationUnit.RevolutionPerMinutePerSecond => (60 / (2 * 3.1415926535897931)) * baseUnitValue, - RotationalAccelerationUnit.RevolutionPerSecondSquared => (1 / (2 * 3.1415926535897931)) * baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalAccelerationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new RotationalAcceleration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RotationalAccelerationUnit.DegreePerSecondSquared => (3.1415926535897931 / 180) * _value, + RotationalAccelerationUnit.RadianPerSecondSquared => _value, + RotationalAccelerationUnit.RevolutionPerMinutePerSecond => ((2 * 3.1415926535897931) / 60) * _value, + RotationalAccelerationUnit.RevolutionPerSecondSquared => (2 * 3.1415926535897931) * _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RotationalAccelerationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RotationalAccelerationUnit.DegreePerSecondSquared => (180 / 3.1415926535897931) * baseUnitValue, + RotationalAccelerationUnit.RadianPerSecondSquared => baseUnitValue, + RotationalAccelerationUnit.RevolutionPerMinutePerSecond => (60 / (2 * 3.1415926535897931)) * baseUnitValue, + RotationalAccelerationUnit.RevolutionPerSecondSquared => (1 / (2 * 3.1415926535897931)) * baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalSpeed.g.cs index b575b551b3..419562634f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -239,77 +239,77 @@ public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalSpeedUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public RotationalSpeed ToUnit(RotationalSpeedUnit unit) - { - var convertedValue = GetValueAs(unit); - return new RotationalSpeed(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RotationalSpeedUnit.CentiradianPerSecond => (_value) * 1e-2d, - RotationalSpeedUnit.DeciradianPerSecond => (_value) * 1e-1d, - RotationalSpeedUnit.DegreePerMinute => (3.1415926535897931 / (180 * 60)) * _value, - RotationalSpeedUnit.DegreePerSecond => (3.1415926535897931 / 180) * _value, - RotationalSpeedUnit.MicrodegreePerSecond => ((3.1415926535897931 / 180) * _value) * 1e-6d, - RotationalSpeedUnit.MicroradianPerSecond => (_value) * 1e-6d, - RotationalSpeedUnit.MillidegreePerSecond => ((3.1415926535897931 / 180) * _value) * 1e-3d, - RotationalSpeedUnit.MilliradianPerSecond => (_value) * 1e-3d, - RotationalSpeedUnit.NanodegreePerSecond => ((3.1415926535897931 / 180) * _value) * 1e-9d, - RotationalSpeedUnit.NanoradianPerSecond => (_value) * 1e-9d, - RotationalSpeedUnit.RadianPerSecond => _value, - RotationalSpeedUnit.RevolutionPerMinute => (_value * 6.2831853072) / 60, - RotationalSpeedUnit.RevolutionPerSecond => _value * 6.2831853072, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RotationalSpeedUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RotationalSpeedUnit.CentiradianPerSecond => (baseUnitValue) / 1e-2d, - RotationalSpeedUnit.DeciradianPerSecond => (baseUnitValue) / 1e-1d, - RotationalSpeedUnit.DegreePerMinute => (180 * 60 / 3.1415926535897931) * baseUnitValue, - RotationalSpeedUnit.DegreePerSecond => (180 / 3.1415926535897931) * baseUnitValue, - RotationalSpeedUnit.MicrodegreePerSecond => ((180 / 3.1415926535897931) * baseUnitValue) / 1e-6d, - RotationalSpeedUnit.MicroradianPerSecond => (baseUnitValue) / 1e-6d, - RotationalSpeedUnit.MillidegreePerSecond => ((180 / 3.1415926535897931) * baseUnitValue) / 1e-3d, - RotationalSpeedUnit.MilliradianPerSecond => (baseUnitValue) / 1e-3d, - RotationalSpeedUnit.NanodegreePerSecond => ((180 / 3.1415926535897931) * baseUnitValue) / 1e-9d, - RotationalSpeedUnit.NanoradianPerSecond => (baseUnitValue) / 1e-9d, - RotationalSpeedUnit.RadianPerSecond => baseUnitValue, - RotationalSpeedUnit.RevolutionPerMinute => (baseUnitValue / 6.2831853072) * 60, - RotationalSpeedUnit.RevolutionPerSecond => baseUnitValue / 6.2831853072, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalSpeedUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public RotationalSpeed ToUnit(RotationalSpeedUnit unit) + { + var convertedValue = GetValueAs(unit); + return new RotationalSpeed(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RotationalSpeedUnit.CentiradianPerSecond => (_value) * 1e-2d, + RotationalSpeedUnit.DeciradianPerSecond => (_value) * 1e-1d, + RotationalSpeedUnit.DegreePerMinute => (3.1415926535897931 / (180 * 60)) * _value, + RotationalSpeedUnit.DegreePerSecond => (3.1415926535897931 / 180) * _value, + RotationalSpeedUnit.MicrodegreePerSecond => ((3.1415926535897931 / 180) * _value) * 1e-6d, + RotationalSpeedUnit.MicroradianPerSecond => (_value) * 1e-6d, + RotationalSpeedUnit.MillidegreePerSecond => ((3.1415926535897931 / 180) * _value) * 1e-3d, + RotationalSpeedUnit.MilliradianPerSecond => (_value) * 1e-3d, + RotationalSpeedUnit.NanodegreePerSecond => ((3.1415926535897931 / 180) * _value) * 1e-9d, + RotationalSpeedUnit.NanoradianPerSecond => (_value) * 1e-9d, + RotationalSpeedUnit.RadianPerSecond => _value, + RotationalSpeedUnit.RevolutionPerMinute => (_value * 6.2831853072) / 60, + RotationalSpeedUnit.RevolutionPerSecond => _value * 6.2831853072, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RotationalSpeedUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RotationalSpeedUnit.CentiradianPerSecond => (baseUnitValue) / 1e-2d, + RotationalSpeedUnit.DeciradianPerSecond => (baseUnitValue) / 1e-1d, + RotationalSpeedUnit.DegreePerMinute => (180 * 60 / 3.1415926535897931) * baseUnitValue, + RotationalSpeedUnit.DegreePerSecond => (180 / 3.1415926535897931) * baseUnitValue, + RotationalSpeedUnit.MicrodegreePerSecond => ((180 / 3.1415926535897931) * baseUnitValue) / 1e-6d, + RotationalSpeedUnit.MicroradianPerSecond => (baseUnitValue) / 1e-6d, + RotationalSpeedUnit.MillidegreePerSecond => ((180 / 3.1415926535897931) * baseUnitValue) / 1e-3d, + RotationalSpeedUnit.MilliradianPerSecond => (baseUnitValue) / 1e-3d, + RotationalSpeedUnit.NanodegreePerSecond => ((180 / 3.1415926535897931) * baseUnitValue) / 1e-9d, + RotationalSpeedUnit.NanoradianPerSecond => (baseUnitValue) / 1e-9d, + RotationalSpeedUnit.RadianPerSecond => baseUnitValue, + RotationalSpeedUnit.RevolutionPerMinute => (baseUnitValue / 6.2831853072) * 60, + RotationalSpeedUnit.RevolutionPerSecond => baseUnitValue / 6.2831853072, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffness.g.cs index abaf9b67b0..10a396e96c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -459,117 +459,117 @@ public static RotationalStiffness From(double value, RotationalStiffnessUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) - { - var convertedValue = GetValueAs(unit); - return new RotationalStiffness(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RotationalStiffnessUnit.CentinewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-2d, - RotationalStiffnessUnit.CentinewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-2d, - RotationalStiffnessUnit.CentinewtonMillimeterPerRadian => (_value * 0.001) * 1e-2d, - RotationalStiffnessUnit.DecanewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e1d, - RotationalStiffnessUnit.DecanewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e1d, - RotationalStiffnessUnit.DecanewtonMillimeterPerRadian => (_value * 0.001) * 1e1d, - RotationalStiffnessUnit.DecinewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-1d, - RotationalStiffnessUnit.DecinewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-1d, - RotationalStiffnessUnit.DecinewtonMillimeterPerRadian => (_value * 0.001) * 1e-1d, - RotationalStiffnessUnit.KilonewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e3d, - RotationalStiffnessUnit.KilonewtonMeterPerRadian => (_value) * 1e3d, - RotationalStiffnessUnit.KilonewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e3d, - RotationalStiffnessUnit.KilonewtonMillimeterPerRadian => (_value * 0.001) * 1e3d, - RotationalStiffnessUnit.KilopoundForceFootPerDegrees => _value * 77682.6, - RotationalStiffnessUnit.MeganewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e6d, - RotationalStiffnessUnit.MeganewtonMeterPerRadian => (_value) * 1e6d, - RotationalStiffnessUnit.MeganewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e6d, - RotationalStiffnessUnit.MeganewtonMillimeterPerRadian => (_value * 0.001) * 1e6d, - RotationalStiffnessUnit.MicronewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-6d, - RotationalStiffnessUnit.MicronewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-6d, - RotationalStiffnessUnit.MicronewtonMillimeterPerRadian => (_value * 0.001) * 1e-6d, - RotationalStiffnessUnit.MillinewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-3d, - RotationalStiffnessUnit.MillinewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-3d, - RotationalStiffnessUnit.MillinewtonMillimeterPerRadian => (_value * 0.001) * 1e-3d, - RotationalStiffnessUnit.NanonewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-9d, - RotationalStiffnessUnit.NanonewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-9d, - RotationalStiffnessUnit.NanonewtonMillimeterPerRadian => (_value * 0.001) * 1e-9d, - RotationalStiffnessUnit.NewtonMeterPerDegree => _value * (180 / 3.1415926535897931), - RotationalStiffnessUnit.NewtonMeterPerRadian => _value, - RotationalStiffnessUnit.NewtonMillimeterPerDegree => _value * 180 / 3.1415926535897931 * 0.001, - RotationalStiffnessUnit.NewtonMillimeterPerRadian => _value * 0.001, - RotationalStiffnessUnit.PoundForceFeetPerRadian => _value * 1.3558179483314, - RotationalStiffnessUnit.PoundForceFootPerDegrees => _value * 77.6826, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RotationalStiffnessUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RotationalStiffnessUnit.CentinewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-2d, - RotationalStiffnessUnit.CentinewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-2d, - RotationalStiffnessUnit.CentinewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-2d, - RotationalStiffnessUnit.DecanewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e1d, - RotationalStiffnessUnit.DecanewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e1d, - RotationalStiffnessUnit.DecanewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e1d, - RotationalStiffnessUnit.DecinewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-1d, - RotationalStiffnessUnit.DecinewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-1d, - RotationalStiffnessUnit.DecinewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-1d, - RotationalStiffnessUnit.KilonewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e3d, - RotationalStiffnessUnit.KilonewtonMeterPerRadian => (baseUnitValue) / 1e3d, - RotationalStiffnessUnit.KilonewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e3d, - RotationalStiffnessUnit.KilonewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e3d, - RotationalStiffnessUnit.KilopoundForceFootPerDegrees => baseUnitValue / 77682.6, - RotationalStiffnessUnit.MeganewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e6d, - RotationalStiffnessUnit.MeganewtonMeterPerRadian => (baseUnitValue) / 1e6d, - RotationalStiffnessUnit.MeganewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e6d, - RotationalStiffnessUnit.MeganewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e6d, - RotationalStiffnessUnit.MicronewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-6d, - RotationalStiffnessUnit.MicronewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-6d, - RotationalStiffnessUnit.MicronewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-6d, - RotationalStiffnessUnit.MillinewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-3d, - RotationalStiffnessUnit.MillinewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-3d, - RotationalStiffnessUnit.MillinewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-3d, - RotationalStiffnessUnit.NanonewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-9d, - RotationalStiffnessUnit.NanonewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-9d, - RotationalStiffnessUnit.NanonewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-9d, - RotationalStiffnessUnit.NewtonMeterPerDegree => baseUnitValue / (180 / 3.1415926535897931), - RotationalStiffnessUnit.NewtonMeterPerRadian => baseUnitValue, - RotationalStiffnessUnit.NewtonMillimeterPerDegree => baseUnitValue / 180 * 3.1415926535897931 * 1000, - RotationalStiffnessUnit.NewtonMillimeterPerRadian => baseUnitValue * 1000, - RotationalStiffnessUnit.PoundForceFeetPerRadian => baseUnitValue / 1.3558179483314, - RotationalStiffnessUnit.PoundForceFootPerDegrees => baseUnitValue / 77.6826, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalStiffnessUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) + { + var convertedValue = GetValueAs(unit); + return new RotationalStiffness(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RotationalStiffnessUnit.CentinewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-2d, + RotationalStiffnessUnit.CentinewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-2d, + RotationalStiffnessUnit.CentinewtonMillimeterPerRadian => (_value * 0.001) * 1e-2d, + RotationalStiffnessUnit.DecanewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e1d, + RotationalStiffnessUnit.DecanewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e1d, + RotationalStiffnessUnit.DecanewtonMillimeterPerRadian => (_value * 0.001) * 1e1d, + RotationalStiffnessUnit.DecinewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-1d, + RotationalStiffnessUnit.DecinewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-1d, + RotationalStiffnessUnit.DecinewtonMillimeterPerRadian => (_value * 0.001) * 1e-1d, + RotationalStiffnessUnit.KilonewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e3d, + RotationalStiffnessUnit.KilonewtonMeterPerRadian => (_value) * 1e3d, + RotationalStiffnessUnit.KilonewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e3d, + RotationalStiffnessUnit.KilonewtonMillimeterPerRadian => (_value * 0.001) * 1e3d, + RotationalStiffnessUnit.KilopoundForceFootPerDegrees => _value * 77682.6, + RotationalStiffnessUnit.MeganewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e6d, + RotationalStiffnessUnit.MeganewtonMeterPerRadian => (_value) * 1e6d, + RotationalStiffnessUnit.MeganewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e6d, + RotationalStiffnessUnit.MeganewtonMillimeterPerRadian => (_value * 0.001) * 1e6d, + RotationalStiffnessUnit.MicronewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-6d, + RotationalStiffnessUnit.MicronewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-6d, + RotationalStiffnessUnit.MicronewtonMillimeterPerRadian => (_value * 0.001) * 1e-6d, + RotationalStiffnessUnit.MillinewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-3d, + RotationalStiffnessUnit.MillinewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-3d, + RotationalStiffnessUnit.MillinewtonMillimeterPerRadian => (_value * 0.001) * 1e-3d, + RotationalStiffnessUnit.NanonewtonMeterPerDegree => (_value * (180 / 3.1415926535897931)) * 1e-9d, + RotationalStiffnessUnit.NanonewtonMillimeterPerDegree => (_value * 180 / 3.1415926535897931 * 0.001) * 1e-9d, + RotationalStiffnessUnit.NanonewtonMillimeterPerRadian => (_value * 0.001) * 1e-9d, + RotationalStiffnessUnit.NewtonMeterPerDegree => _value * (180 / 3.1415926535897931), + RotationalStiffnessUnit.NewtonMeterPerRadian => _value, + RotationalStiffnessUnit.NewtonMillimeterPerDegree => _value * 180 / 3.1415926535897931 * 0.001, + RotationalStiffnessUnit.NewtonMillimeterPerRadian => _value * 0.001, + RotationalStiffnessUnit.PoundForceFeetPerRadian => _value * 1.3558179483314, + RotationalStiffnessUnit.PoundForceFootPerDegrees => _value * 77.6826, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RotationalStiffnessUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RotationalStiffnessUnit.CentinewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-2d, + RotationalStiffnessUnit.CentinewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-2d, + RotationalStiffnessUnit.CentinewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-2d, + RotationalStiffnessUnit.DecanewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e1d, + RotationalStiffnessUnit.DecanewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e1d, + RotationalStiffnessUnit.DecanewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e1d, + RotationalStiffnessUnit.DecinewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-1d, + RotationalStiffnessUnit.DecinewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-1d, + RotationalStiffnessUnit.DecinewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-1d, + RotationalStiffnessUnit.KilonewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e3d, + RotationalStiffnessUnit.KilonewtonMeterPerRadian => (baseUnitValue) / 1e3d, + RotationalStiffnessUnit.KilonewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e3d, + RotationalStiffnessUnit.KilonewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e3d, + RotationalStiffnessUnit.KilopoundForceFootPerDegrees => baseUnitValue / 77682.6, + RotationalStiffnessUnit.MeganewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e6d, + RotationalStiffnessUnit.MeganewtonMeterPerRadian => (baseUnitValue) / 1e6d, + RotationalStiffnessUnit.MeganewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e6d, + RotationalStiffnessUnit.MeganewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e6d, + RotationalStiffnessUnit.MicronewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-6d, + RotationalStiffnessUnit.MicronewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-6d, + RotationalStiffnessUnit.MicronewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-6d, + RotationalStiffnessUnit.MillinewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-3d, + RotationalStiffnessUnit.MillinewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-3d, + RotationalStiffnessUnit.MillinewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-3d, + RotationalStiffnessUnit.NanonewtonMeterPerDegree => (baseUnitValue / (180 / 3.1415926535897931)) / 1e-9d, + RotationalStiffnessUnit.NanonewtonMillimeterPerDegree => (baseUnitValue / 180 * 3.1415926535897931 * 1000) / 1e-9d, + RotationalStiffnessUnit.NanonewtonMillimeterPerRadian => (baseUnitValue * 1000) / 1e-9d, + RotationalStiffnessUnit.NewtonMeterPerDegree => baseUnitValue / (180 / 3.1415926535897931), + RotationalStiffnessUnit.NewtonMeterPerRadian => baseUnitValue, + RotationalStiffnessUnit.NewtonMillimeterPerDegree => baseUnitValue / 180 * 3.1415926535897931 * 1000, + RotationalStiffnessUnit.NewtonMillimeterPerRadian => baseUnitValue * 1000, + RotationalStiffnessUnit.PoundForceFeetPerRadian => baseUnitValue / 1.3558179483314, + RotationalStiffnessUnit.PoundForceFootPerDegrees => baseUnitValue / 77.6826, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index e124142709..5d9d52fd6f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -151,61 +151,61 @@ public static RotationalStiffnessPerLength From(double value, RotationalStiffnes #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessPerLengthUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) - { - var convertedValue = GetValueAs(unit); - return new RotationalStiffnessPerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter => (_value) * 1e3d, - RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot => _value * 254864.324570, - RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter => (_value) * 1e6d, - RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter => _value, - RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot => _value * 254.864324570, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(RotationalStiffnessPerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter => (baseUnitValue) / 1e3d, - RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot => baseUnitValue / 254864.324570, - RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter => (baseUnitValue) / 1e6d, - RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter => baseUnitValue, - RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot => baseUnitValue / 254.864324570, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(RotationalStiffnessPerLengthUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) + { + var convertedValue = GetValueAs(unit); + return new RotationalStiffnessPerLength(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter => (_value) * 1e3d, + RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot => _value * 254864.324570, + RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter => (_value) * 1e6d, + RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter => _value, + RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot => _value * 254.864324570, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(RotationalStiffnessPerLengthUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter => (baseUnitValue) / 1e3d, + RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot => baseUnitValue / 254864.324570, + RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter => (baseUnitValue) / 1e6d, + RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter => baseUnitValue, + RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot => baseUnitValue / 254.864324570, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Scalar.g.cs index 561ac9377c..544ef6c9d4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Scalar.g.cs @@ -107,53 +107,53 @@ public static Scalar From(double value, ScalarUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ScalarUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Scalar ToUnit(ScalarUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Scalar(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ScalarUnit.Amount => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ScalarUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ScalarUnit.Amount => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ScalarUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Scalar ToUnit(ScalarUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Scalar(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ScalarUnit.Amount => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ScalarUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ScalarUnit.Amount => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SolidAngle.g.cs index b6cb5885a4..43ceaaeb9a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SolidAngle.g.cs @@ -110,53 +110,53 @@ public static SolidAngle From(double value, SolidAngleUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SolidAngleUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public SolidAngle ToUnit(SolidAngleUnit unit) - { - var convertedValue = GetValueAs(unit); - return new SolidAngle(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SolidAngleUnit.Steradian => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SolidAngleUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SolidAngleUnit.Steradian => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SolidAngleUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public SolidAngle ToUnit(SolidAngleUnit unit) + { + var convertedValue = GetValueAs(unit); + return new SolidAngle(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SolidAngleUnit.Steradian => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SolidAngleUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SolidAngleUnit.Steradian => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEnergy.g.cs index a06cefa9d5..9d1b9a3775 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -418,109 +418,109 @@ public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEnergyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public SpecificEnergy ToUnit(SpecificEnergyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new SpecificEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SpecificEnergyUnit.BtuPerPound => _value * 2326.000075362, - SpecificEnergyUnit.CaloriePerGram => _value * 4.184e3, - SpecificEnergyUnit.GigawattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e9d, - SpecificEnergyUnit.GigawattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e9d, - SpecificEnergyUnit.GigawattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e9d, - SpecificEnergyUnit.GigawattHourPerKilogram => (_value * 3.6e3) * 1e9d, - SpecificEnergyUnit.GigawattHourPerPound => (_value * 7.93664e3) * 1e9d, - SpecificEnergyUnit.JoulePerKilogram => _value, - SpecificEnergyUnit.KilocaloriePerGram => (_value * 4.184e3) * 1e3d, - SpecificEnergyUnit.KilojoulePerKilogram => (_value) * 1e3d, - SpecificEnergyUnit.KilowattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e3d, - SpecificEnergyUnit.KilowattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e3d, - SpecificEnergyUnit.KilowattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e3d, - SpecificEnergyUnit.KilowattHourPerKilogram => (_value * 3.6e3) * 1e3d, - SpecificEnergyUnit.KilowattHourPerPound => (_value * 7.93664e3) * 1e3d, - SpecificEnergyUnit.MegajoulePerKilogram => (_value) * 1e6d, - SpecificEnergyUnit.MegawattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e6d, - SpecificEnergyUnit.MegawattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e6d, - SpecificEnergyUnit.MegawattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e6d, - SpecificEnergyUnit.MegawattHourPerKilogram => (_value * 3.6e3) * 1e6d, - SpecificEnergyUnit.MegawattHourPerPound => (_value * 7.93664e3) * 1e6d, - SpecificEnergyUnit.TerawattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e12d, - SpecificEnergyUnit.TerawattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e12d, - SpecificEnergyUnit.TerawattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e12d, - SpecificEnergyUnit.WattDayPerKilogram => _value * (24 * 3.6e3), - SpecificEnergyUnit.WattDayPerShortTon => _value * ((24 * 3.6e3) / 9.0718474e2), - SpecificEnergyUnit.WattDayPerTonne => _value * ((24 * 3.6e3) / 1e3), - SpecificEnergyUnit.WattHourPerKilogram => _value * 3.6e3, - SpecificEnergyUnit.WattHourPerPound => _value * 7.93664e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SpecificEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SpecificEnergyUnit.BtuPerPound => baseUnitValue / 2326.000075362, - SpecificEnergyUnit.CaloriePerGram => baseUnitValue / 4.184e3, - SpecificEnergyUnit.GigawattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e9d, - SpecificEnergyUnit.GigawattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e9d, - SpecificEnergyUnit.GigawattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e9d, - SpecificEnergyUnit.GigawattHourPerKilogram => (baseUnitValue / 3.6e3) / 1e9d, - SpecificEnergyUnit.GigawattHourPerPound => (baseUnitValue / 7.93664e3) / 1e9d, - SpecificEnergyUnit.JoulePerKilogram => baseUnitValue, - SpecificEnergyUnit.KilocaloriePerGram => (baseUnitValue / 4.184e3) / 1e3d, - SpecificEnergyUnit.KilojoulePerKilogram => (baseUnitValue) / 1e3d, - SpecificEnergyUnit.KilowattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e3d, - SpecificEnergyUnit.KilowattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e3d, - SpecificEnergyUnit.KilowattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e3d, - SpecificEnergyUnit.KilowattHourPerKilogram => (baseUnitValue / 3.6e3) / 1e3d, - SpecificEnergyUnit.KilowattHourPerPound => (baseUnitValue / 7.93664e3) / 1e3d, - SpecificEnergyUnit.MegajoulePerKilogram => (baseUnitValue) / 1e6d, - SpecificEnergyUnit.MegawattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e6d, - SpecificEnergyUnit.MegawattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e6d, - SpecificEnergyUnit.MegawattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e6d, - SpecificEnergyUnit.MegawattHourPerKilogram => (baseUnitValue / 3.6e3) / 1e6d, - SpecificEnergyUnit.MegawattHourPerPound => (baseUnitValue / 7.93664e3) / 1e6d, - SpecificEnergyUnit.TerawattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e12d, - SpecificEnergyUnit.TerawattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e12d, - SpecificEnergyUnit.TerawattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e12d, - SpecificEnergyUnit.WattDayPerKilogram => baseUnitValue / (24 * 3.6e3), - SpecificEnergyUnit.WattDayPerShortTon => baseUnitValue / ((24 * 3.6e3) / 9.0718474e2), - SpecificEnergyUnit.WattDayPerTonne => baseUnitValue / ((24 * 3.6e3) / 1e3), - SpecificEnergyUnit.WattHourPerKilogram => baseUnitValue / 3.6e3, - SpecificEnergyUnit.WattHourPerPound => baseUnitValue / 7.93664e3, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificEnergyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public SpecificEnergy ToUnit(SpecificEnergyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new SpecificEnergy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SpecificEnergyUnit.BtuPerPound => _value * 2326.000075362, + SpecificEnergyUnit.CaloriePerGram => _value * 4.184e3, + SpecificEnergyUnit.GigawattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e9d, + SpecificEnergyUnit.GigawattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e9d, + SpecificEnergyUnit.GigawattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e9d, + SpecificEnergyUnit.GigawattHourPerKilogram => (_value * 3.6e3) * 1e9d, + SpecificEnergyUnit.GigawattHourPerPound => (_value * 7.93664e3) * 1e9d, + SpecificEnergyUnit.JoulePerKilogram => _value, + SpecificEnergyUnit.KilocaloriePerGram => (_value * 4.184e3) * 1e3d, + SpecificEnergyUnit.KilojoulePerKilogram => (_value) * 1e3d, + SpecificEnergyUnit.KilowattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e3d, + SpecificEnergyUnit.KilowattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e3d, + SpecificEnergyUnit.KilowattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e3d, + SpecificEnergyUnit.KilowattHourPerKilogram => (_value * 3.6e3) * 1e3d, + SpecificEnergyUnit.KilowattHourPerPound => (_value * 7.93664e3) * 1e3d, + SpecificEnergyUnit.MegajoulePerKilogram => (_value) * 1e6d, + SpecificEnergyUnit.MegawattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e6d, + SpecificEnergyUnit.MegawattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e6d, + SpecificEnergyUnit.MegawattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e6d, + SpecificEnergyUnit.MegawattHourPerKilogram => (_value * 3.6e3) * 1e6d, + SpecificEnergyUnit.MegawattHourPerPound => (_value * 7.93664e3) * 1e6d, + SpecificEnergyUnit.TerawattDayPerKilogram => (_value * (24 * 3.6e3)) * 1e12d, + SpecificEnergyUnit.TerawattDayPerShortTon => (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e12d, + SpecificEnergyUnit.TerawattDayPerTonne => (_value * ((24 * 3.6e3) / 1e3)) * 1e12d, + SpecificEnergyUnit.WattDayPerKilogram => _value * (24 * 3.6e3), + SpecificEnergyUnit.WattDayPerShortTon => _value * ((24 * 3.6e3) / 9.0718474e2), + SpecificEnergyUnit.WattDayPerTonne => _value * ((24 * 3.6e3) / 1e3), + SpecificEnergyUnit.WattHourPerKilogram => _value * 3.6e3, + SpecificEnergyUnit.WattHourPerPound => _value * 7.93664e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SpecificEnergyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SpecificEnergyUnit.BtuPerPound => baseUnitValue / 2326.000075362, + SpecificEnergyUnit.CaloriePerGram => baseUnitValue / 4.184e3, + SpecificEnergyUnit.GigawattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e9d, + SpecificEnergyUnit.GigawattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e9d, + SpecificEnergyUnit.GigawattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e9d, + SpecificEnergyUnit.GigawattHourPerKilogram => (baseUnitValue / 3.6e3) / 1e9d, + SpecificEnergyUnit.GigawattHourPerPound => (baseUnitValue / 7.93664e3) / 1e9d, + SpecificEnergyUnit.JoulePerKilogram => baseUnitValue, + SpecificEnergyUnit.KilocaloriePerGram => (baseUnitValue / 4.184e3) / 1e3d, + SpecificEnergyUnit.KilojoulePerKilogram => (baseUnitValue) / 1e3d, + SpecificEnergyUnit.KilowattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e3d, + SpecificEnergyUnit.KilowattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e3d, + SpecificEnergyUnit.KilowattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e3d, + SpecificEnergyUnit.KilowattHourPerKilogram => (baseUnitValue / 3.6e3) / 1e3d, + SpecificEnergyUnit.KilowattHourPerPound => (baseUnitValue / 7.93664e3) / 1e3d, + SpecificEnergyUnit.MegajoulePerKilogram => (baseUnitValue) / 1e6d, + SpecificEnergyUnit.MegawattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e6d, + SpecificEnergyUnit.MegawattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e6d, + SpecificEnergyUnit.MegawattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e6d, + SpecificEnergyUnit.MegawattHourPerKilogram => (baseUnitValue / 3.6e3) / 1e6d, + SpecificEnergyUnit.MegawattHourPerPound => (baseUnitValue / 7.93664e3) / 1e6d, + SpecificEnergyUnit.TerawattDayPerKilogram => (baseUnitValue / (24 * 3.6e3)) / 1e12d, + SpecificEnergyUnit.TerawattDayPerShortTon => (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e12d, + SpecificEnergyUnit.TerawattDayPerTonne => (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e12d, + SpecificEnergyUnit.WattDayPerKilogram => baseUnitValue / (24 * 3.6e3), + SpecificEnergyUnit.WattDayPerShortTon => baseUnitValue / ((24 * 3.6e3) / 9.0718474e2), + SpecificEnergyUnit.WattDayPerTonne => baseUnitValue / ((24 * 3.6e3) / 1e3), + SpecificEnergyUnit.WattHourPerKilogram => baseUnitValue / 3.6e3, + SpecificEnergyUnit.WattHourPerPound => baseUnitValue / 7.93664e3, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEntropy.g.cs index bafe371ef0..fe784bc916 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -195,69 +195,69 @@ public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEntropyUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public SpecificEntropy ToUnit(SpecificEntropyUnit unit) - { - var convertedValue = GetValueAs(unit); - return new SpecificEntropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SpecificEntropyUnit.BtuPerPoundFahrenheit => _value * 4.1868e3, - SpecificEntropyUnit.CaloriePerGramKelvin => _value * 4.184e3, - SpecificEntropyUnit.JoulePerKilogramDegreeCelsius => _value, - SpecificEntropyUnit.JoulePerKilogramKelvin => _value, - SpecificEntropyUnit.KilocaloriePerGramKelvin => (_value * 4.184e3) * 1e3d, - SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius => (_value) * 1e3d, - SpecificEntropyUnit.KilojoulePerKilogramKelvin => (_value) * 1e3d, - SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius => (_value) * 1e6d, - SpecificEntropyUnit.MegajoulePerKilogramKelvin => (_value) * 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SpecificEntropyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SpecificEntropyUnit.BtuPerPoundFahrenheit => baseUnitValue / 4.1868e3, - SpecificEntropyUnit.CaloriePerGramKelvin => baseUnitValue / 4.184e3, - SpecificEntropyUnit.JoulePerKilogramDegreeCelsius => baseUnitValue, - SpecificEntropyUnit.JoulePerKilogramKelvin => baseUnitValue, - SpecificEntropyUnit.KilocaloriePerGramKelvin => (baseUnitValue / 4.184e3) / 1e3d, - SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius => (baseUnitValue) / 1e3d, - SpecificEntropyUnit.KilojoulePerKilogramKelvin => (baseUnitValue) / 1e3d, - SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius => (baseUnitValue) / 1e6d, - SpecificEntropyUnit.MegajoulePerKilogramKelvin => (baseUnitValue) / 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificEntropyUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public SpecificEntropy ToUnit(SpecificEntropyUnit unit) + { + var convertedValue = GetValueAs(unit); + return new SpecificEntropy(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SpecificEntropyUnit.BtuPerPoundFahrenheit => _value * 4.1868e3, + SpecificEntropyUnit.CaloriePerGramKelvin => _value * 4.184e3, + SpecificEntropyUnit.JoulePerKilogramDegreeCelsius => _value, + SpecificEntropyUnit.JoulePerKilogramKelvin => _value, + SpecificEntropyUnit.KilocaloriePerGramKelvin => (_value * 4.184e3) * 1e3d, + SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius => (_value) * 1e3d, + SpecificEntropyUnit.KilojoulePerKilogramKelvin => (_value) * 1e3d, + SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius => (_value) * 1e6d, + SpecificEntropyUnit.MegajoulePerKilogramKelvin => (_value) * 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SpecificEntropyUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SpecificEntropyUnit.BtuPerPoundFahrenheit => baseUnitValue / 4.1868e3, + SpecificEntropyUnit.CaloriePerGramKelvin => baseUnitValue / 4.184e3, + SpecificEntropyUnit.JoulePerKilogramDegreeCelsius => baseUnitValue, + SpecificEntropyUnit.JoulePerKilogramKelvin => baseUnitValue, + SpecificEntropyUnit.KilocaloriePerGramKelvin => (baseUnitValue / 4.184e3) / 1e3d, + SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius => (baseUnitValue) / 1e3d, + SpecificEntropyUnit.KilojoulePerKilogramKelvin => (baseUnitValue) / 1e3d, + SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius => (baseUnitValue) / 1e6d, + SpecificEntropyUnit.MegajoulePerKilogramKelvin => (baseUnitValue) / 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index 9cb1dd7ff6..9d4dce3e04 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -143,59 +143,59 @@ public static SpecificFuelConsumption From(double value, SpecificFuelConsumption #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificFuelConsumptionUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit) - { - var convertedValue = GetValueAs(unit); - return new SpecificFuelConsumption(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond => _value, - SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour => _value * 28.33, - SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond => (_value) * 1e3d, - SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour => _value * 28.33, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond => baseUnitValue, - SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour => baseUnitValue / 28.33, - SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond => (baseUnitValue) / 1e3d, - SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour => baseUnitValue / 28.33, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificFuelConsumptionUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit) + { + var convertedValue = GetValueAs(unit); + return new SpecificFuelConsumption(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond => _value, + SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour => _value * 28.33, + SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond => (_value) * 1e3d, + SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour => _value * 28.33, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SpecificFuelConsumptionUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond => baseUnitValue, + SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour => baseUnitValue / 28.33, + SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond => (baseUnitValue) / 1e3d, + SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour => baseUnitValue / 28.33, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificVolume.g.cs index 2e39b0c294..2f44a03d6d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -129,57 +129,57 @@ public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificVolumeUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public SpecificVolume ToUnit(SpecificVolumeUnit unit) - { - var convertedValue = GetValueAs(unit); - return new SpecificVolume(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SpecificVolumeUnit.CubicFootPerPound => _value / 16.01846353, - SpecificVolumeUnit.CubicMeterPerKilogram => _value, - SpecificVolumeUnit.MillicubicMeterPerKilogram => (_value) * 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SpecificVolumeUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SpecificVolumeUnit.CubicFootPerPound => baseUnitValue * 16.01846353, - SpecificVolumeUnit.CubicMeterPerKilogram => baseUnitValue, - SpecificVolumeUnit.MillicubicMeterPerKilogram => (baseUnitValue) / 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificVolumeUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public SpecificVolume ToUnit(SpecificVolumeUnit unit) + { + var convertedValue = GetValueAs(unit); + return new SpecificVolume(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SpecificVolumeUnit.CubicFootPerPound => _value / 16.01846353, + SpecificVolumeUnit.CubicMeterPerKilogram => _value, + SpecificVolumeUnit.MillicubicMeterPerKilogram => (_value) * 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SpecificVolumeUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SpecificVolumeUnit.CubicFootPerPound => baseUnitValue * 16.01846353, + SpecificVolumeUnit.CubicMeterPerKilogram => baseUnitValue, + SpecificVolumeUnit.MillicubicMeterPerKilogram => (baseUnitValue) / 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificWeight.g.cs index 6742af4a4c..fe32b5b7ef 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -286,85 +286,85 @@ public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificWeightUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public SpecificWeight ToUnit(SpecificWeightUnit unit) - { - var convertedValue = GetValueAs(unit); - return new SpecificWeight(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SpecificWeightUnit.KilogramForcePerCubicCentimeter => _value * 9.80665e6, - SpecificWeightUnit.KilogramForcePerCubicMeter => _value * 9.80665, - SpecificWeightUnit.KilogramForcePerCubicMillimeter => _value * 9.80665e9, - SpecificWeightUnit.KilonewtonPerCubicCentimeter => (_value * 1000000) * 1e3d, - SpecificWeightUnit.KilonewtonPerCubicMeter => (_value) * 1e3d, - SpecificWeightUnit.KilonewtonPerCubicMillimeter => (_value * 1000000000) * 1e3d, - SpecificWeightUnit.KilopoundForcePerCubicFoot => (_value * 1.570874638462462e2) * 1e3d, - SpecificWeightUnit.KilopoundForcePerCubicInch => (_value * 2.714471375263134e5) * 1e3d, - SpecificWeightUnit.MeganewtonPerCubicMeter => (_value) * 1e6d, - SpecificWeightUnit.NewtonPerCubicCentimeter => _value * 1000000, - SpecificWeightUnit.NewtonPerCubicMeter => _value, - SpecificWeightUnit.NewtonPerCubicMillimeter => _value * 1000000000, - SpecificWeightUnit.PoundForcePerCubicFoot => _value * 1.570874638462462e2, - SpecificWeightUnit.PoundForcePerCubicInch => _value * 2.714471375263134e5, - SpecificWeightUnit.TonneForcePerCubicCentimeter => _value * 9.80665e9, - SpecificWeightUnit.TonneForcePerCubicMeter => _value * 9.80665e3, - SpecificWeightUnit.TonneForcePerCubicMillimeter => _value * 9.80665e12, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SpecificWeightUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SpecificWeightUnit.KilogramForcePerCubicCentimeter => baseUnitValue / 9.80665e6, - SpecificWeightUnit.KilogramForcePerCubicMeter => baseUnitValue / 9.80665, - SpecificWeightUnit.KilogramForcePerCubicMillimeter => baseUnitValue / 9.80665e9, - SpecificWeightUnit.KilonewtonPerCubicCentimeter => (baseUnitValue * 0.000001) / 1e3d, - SpecificWeightUnit.KilonewtonPerCubicMeter => (baseUnitValue) / 1e3d, - SpecificWeightUnit.KilonewtonPerCubicMillimeter => (baseUnitValue * 0.000000001) / 1e3d, - SpecificWeightUnit.KilopoundForcePerCubicFoot => (baseUnitValue / 1.570874638462462e2) / 1e3d, - SpecificWeightUnit.KilopoundForcePerCubicInch => (baseUnitValue / 2.714471375263134e5) / 1e3d, - SpecificWeightUnit.MeganewtonPerCubicMeter => (baseUnitValue) / 1e6d, - SpecificWeightUnit.NewtonPerCubicCentimeter => baseUnitValue * 0.000001, - SpecificWeightUnit.NewtonPerCubicMeter => baseUnitValue, - SpecificWeightUnit.NewtonPerCubicMillimeter => baseUnitValue * 0.000000001, - SpecificWeightUnit.PoundForcePerCubicFoot => baseUnitValue / 1.570874638462462e2, - SpecificWeightUnit.PoundForcePerCubicInch => baseUnitValue / 2.714471375263134e5, - SpecificWeightUnit.TonneForcePerCubicCentimeter => baseUnitValue / 9.80665e9, - SpecificWeightUnit.TonneForcePerCubicMeter => baseUnitValue / 9.80665e3, - SpecificWeightUnit.TonneForcePerCubicMillimeter => baseUnitValue / 9.80665e12, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpecificWeightUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public SpecificWeight ToUnit(SpecificWeightUnit unit) + { + var convertedValue = GetValueAs(unit); + return new SpecificWeight(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SpecificWeightUnit.KilogramForcePerCubicCentimeter => _value * 9.80665e6, + SpecificWeightUnit.KilogramForcePerCubicMeter => _value * 9.80665, + SpecificWeightUnit.KilogramForcePerCubicMillimeter => _value * 9.80665e9, + SpecificWeightUnit.KilonewtonPerCubicCentimeter => (_value * 1000000) * 1e3d, + SpecificWeightUnit.KilonewtonPerCubicMeter => (_value) * 1e3d, + SpecificWeightUnit.KilonewtonPerCubicMillimeter => (_value * 1000000000) * 1e3d, + SpecificWeightUnit.KilopoundForcePerCubicFoot => (_value * 1.570874638462462e2) * 1e3d, + SpecificWeightUnit.KilopoundForcePerCubicInch => (_value * 2.714471375263134e5) * 1e3d, + SpecificWeightUnit.MeganewtonPerCubicMeter => (_value) * 1e6d, + SpecificWeightUnit.NewtonPerCubicCentimeter => _value * 1000000, + SpecificWeightUnit.NewtonPerCubicMeter => _value, + SpecificWeightUnit.NewtonPerCubicMillimeter => _value * 1000000000, + SpecificWeightUnit.PoundForcePerCubicFoot => _value * 1.570874638462462e2, + SpecificWeightUnit.PoundForcePerCubicInch => _value * 2.714471375263134e5, + SpecificWeightUnit.TonneForcePerCubicCentimeter => _value * 9.80665e9, + SpecificWeightUnit.TonneForcePerCubicMeter => _value * 9.80665e3, + SpecificWeightUnit.TonneForcePerCubicMillimeter => _value * 9.80665e12, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SpecificWeightUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SpecificWeightUnit.KilogramForcePerCubicCentimeter => baseUnitValue / 9.80665e6, + SpecificWeightUnit.KilogramForcePerCubicMeter => baseUnitValue / 9.80665, + SpecificWeightUnit.KilogramForcePerCubicMillimeter => baseUnitValue / 9.80665e9, + SpecificWeightUnit.KilonewtonPerCubicCentimeter => (baseUnitValue * 0.000001) / 1e3d, + SpecificWeightUnit.KilonewtonPerCubicMeter => (baseUnitValue) / 1e3d, + SpecificWeightUnit.KilonewtonPerCubicMillimeter => (baseUnitValue * 0.000000001) / 1e3d, + SpecificWeightUnit.KilopoundForcePerCubicFoot => (baseUnitValue / 1.570874638462462e2) / 1e3d, + SpecificWeightUnit.KilopoundForcePerCubicInch => (baseUnitValue / 2.714471375263134e5) / 1e3d, + SpecificWeightUnit.MeganewtonPerCubicMeter => (baseUnitValue) / 1e6d, + SpecificWeightUnit.NewtonPerCubicCentimeter => baseUnitValue * 0.000001, + SpecificWeightUnit.NewtonPerCubicMeter => baseUnitValue, + SpecificWeightUnit.NewtonPerCubicMillimeter => baseUnitValue * 0.000000001, + SpecificWeightUnit.PoundForcePerCubicFoot => baseUnitValue / 1.570874638462462e2, + SpecificWeightUnit.PoundForcePerCubicInch => baseUnitValue / 2.714471375263134e5, + SpecificWeightUnit.TonneForcePerCubicCentimeter => baseUnitValue / 9.80665e9, + SpecificWeightUnit.TonneForcePerCubicMeter => baseUnitValue / 9.80665e3, + SpecificWeightUnit.TonneForcePerCubicMillimeter => baseUnitValue / 9.80665e12, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Speed.g.cs index ec37bfecc6..02b236fd2b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Speed.g.cs @@ -459,117 +459,117 @@ public static Speed From(double value, SpeedUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpeedUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Speed ToUnit(SpeedUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Speed(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - SpeedUnit.CentimeterPerHour => (_value / 3600) * 1e-2d, - SpeedUnit.CentimeterPerMinute => (_value / 60) * 1e-2d, - SpeedUnit.CentimeterPerSecond => (_value) * 1e-2d, - SpeedUnit.DecimeterPerMinute => (_value / 60) * 1e-1d, - SpeedUnit.DecimeterPerSecond => (_value) * 1e-1d, - SpeedUnit.FootPerHour => _value * 0.3048 / 3600, - SpeedUnit.FootPerMinute => _value * 0.3048 / 60, - SpeedUnit.FootPerSecond => _value * 0.3048, - SpeedUnit.InchPerHour => (_value / 3600) * 2.54e-2, - SpeedUnit.InchPerMinute => (_value / 60) * 2.54e-2, - SpeedUnit.InchPerSecond => _value * 2.54e-2, - SpeedUnit.KilometerPerHour => (_value / 3600) * 1e3d, - SpeedUnit.KilometerPerMinute => (_value / 60) * 1e3d, - SpeedUnit.KilometerPerSecond => (_value) * 1e3d, - SpeedUnit.Knot => _value * 0.514444, - SpeedUnit.Mach => _value * 340.29, - SpeedUnit.MeterPerHour => _value / 3600, - SpeedUnit.MeterPerMinute => _value / 60, - SpeedUnit.MeterPerSecond => _value, - SpeedUnit.MicrometerPerMinute => (_value / 60) * 1e-6d, - SpeedUnit.MicrometerPerSecond => (_value) * 1e-6d, - SpeedUnit.MilePerHour => _value * 0.44704, - SpeedUnit.MillimeterPerHour => (_value / 3600) * 1e-3d, - SpeedUnit.MillimeterPerMinute => (_value / 60) * 1e-3d, - SpeedUnit.MillimeterPerSecond => (_value) * 1e-3d, - SpeedUnit.NanometerPerMinute => (_value / 60) * 1e-9d, - SpeedUnit.NanometerPerSecond => (_value) * 1e-9d, - SpeedUnit.UsSurveyFootPerHour => (_value * 1200 / 3937) / 3600, - SpeedUnit.UsSurveyFootPerMinute => (_value * 1200 / 3937) / 60, - SpeedUnit.UsSurveyFootPerSecond => _value * 1200 / 3937, - SpeedUnit.YardPerHour => _value * 0.9144 / 3600, - SpeedUnit.YardPerMinute => _value * 0.9144 / 60, - SpeedUnit.YardPerSecond => _value * 0.9144, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(SpeedUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - SpeedUnit.CentimeterPerHour => (baseUnitValue * 3600) / 1e-2d, - SpeedUnit.CentimeterPerMinute => (baseUnitValue * 60) / 1e-2d, - SpeedUnit.CentimeterPerSecond => (baseUnitValue) / 1e-2d, - SpeedUnit.DecimeterPerMinute => (baseUnitValue * 60) / 1e-1d, - SpeedUnit.DecimeterPerSecond => (baseUnitValue) / 1e-1d, - SpeedUnit.FootPerHour => baseUnitValue / 0.3048 * 3600, - SpeedUnit.FootPerMinute => baseUnitValue / 0.3048 * 60, - SpeedUnit.FootPerSecond => baseUnitValue / 0.3048, - SpeedUnit.InchPerHour => (baseUnitValue / 2.54e-2) * 3600, - SpeedUnit.InchPerMinute => (baseUnitValue / 2.54e-2) * 60, - SpeedUnit.InchPerSecond => baseUnitValue / 2.54e-2, - SpeedUnit.KilometerPerHour => (baseUnitValue * 3600) / 1e3d, - SpeedUnit.KilometerPerMinute => (baseUnitValue * 60) / 1e3d, - SpeedUnit.KilometerPerSecond => (baseUnitValue) / 1e3d, - SpeedUnit.Knot => baseUnitValue / 0.514444, - SpeedUnit.Mach => baseUnitValue / 340.29, - SpeedUnit.MeterPerHour => baseUnitValue * 3600, - SpeedUnit.MeterPerMinute => baseUnitValue * 60, - SpeedUnit.MeterPerSecond => baseUnitValue, - SpeedUnit.MicrometerPerMinute => (baseUnitValue * 60) / 1e-6d, - SpeedUnit.MicrometerPerSecond => (baseUnitValue) / 1e-6d, - SpeedUnit.MilePerHour => baseUnitValue / 0.44704, - SpeedUnit.MillimeterPerHour => (baseUnitValue * 3600) / 1e-3d, - SpeedUnit.MillimeterPerMinute => (baseUnitValue * 60) / 1e-3d, - SpeedUnit.MillimeterPerSecond => (baseUnitValue) / 1e-3d, - SpeedUnit.NanometerPerMinute => (baseUnitValue * 60) / 1e-9d, - SpeedUnit.NanometerPerSecond => (baseUnitValue) / 1e-9d, - SpeedUnit.UsSurveyFootPerHour => (baseUnitValue * 3937 / 1200) * 3600, - SpeedUnit.UsSurveyFootPerMinute => (baseUnitValue * 3937 / 1200) * 60, - SpeedUnit.UsSurveyFootPerSecond => baseUnitValue * 3937 / 1200, - SpeedUnit.YardPerHour => baseUnitValue / 0.9144 * 3600, - SpeedUnit.YardPerMinute => baseUnitValue / 0.9144 * 60, - SpeedUnit.YardPerSecond => baseUnitValue / 0.9144, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(SpeedUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Speed ToUnit(SpeedUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Speed(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + SpeedUnit.CentimeterPerHour => (_value / 3600) * 1e-2d, + SpeedUnit.CentimeterPerMinute => (_value / 60) * 1e-2d, + SpeedUnit.CentimeterPerSecond => (_value) * 1e-2d, + SpeedUnit.DecimeterPerMinute => (_value / 60) * 1e-1d, + SpeedUnit.DecimeterPerSecond => (_value) * 1e-1d, + SpeedUnit.FootPerHour => _value * 0.3048 / 3600, + SpeedUnit.FootPerMinute => _value * 0.3048 / 60, + SpeedUnit.FootPerSecond => _value * 0.3048, + SpeedUnit.InchPerHour => (_value / 3600) * 2.54e-2, + SpeedUnit.InchPerMinute => (_value / 60) * 2.54e-2, + SpeedUnit.InchPerSecond => _value * 2.54e-2, + SpeedUnit.KilometerPerHour => (_value / 3600) * 1e3d, + SpeedUnit.KilometerPerMinute => (_value / 60) * 1e3d, + SpeedUnit.KilometerPerSecond => (_value) * 1e3d, + SpeedUnit.Knot => _value * 0.514444, + SpeedUnit.Mach => _value * 340.29, + SpeedUnit.MeterPerHour => _value / 3600, + SpeedUnit.MeterPerMinute => _value / 60, + SpeedUnit.MeterPerSecond => _value, + SpeedUnit.MicrometerPerMinute => (_value / 60) * 1e-6d, + SpeedUnit.MicrometerPerSecond => (_value) * 1e-6d, + SpeedUnit.MilePerHour => _value * 0.44704, + SpeedUnit.MillimeterPerHour => (_value / 3600) * 1e-3d, + SpeedUnit.MillimeterPerMinute => (_value / 60) * 1e-3d, + SpeedUnit.MillimeterPerSecond => (_value) * 1e-3d, + SpeedUnit.NanometerPerMinute => (_value / 60) * 1e-9d, + SpeedUnit.NanometerPerSecond => (_value) * 1e-9d, + SpeedUnit.UsSurveyFootPerHour => (_value * 1200 / 3937) / 3600, + SpeedUnit.UsSurveyFootPerMinute => (_value * 1200 / 3937) / 60, + SpeedUnit.UsSurveyFootPerSecond => _value * 1200 / 3937, + SpeedUnit.YardPerHour => _value * 0.9144 / 3600, + SpeedUnit.YardPerMinute => _value * 0.9144 / 60, + SpeedUnit.YardPerSecond => _value * 0.9144, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(SpeedUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + SpeedUnit.CentimeterPerHour => (baseUnitValue * 3600) / 1e-2d, + SpeedUnit.CentimeterPerMinute => (baseUnitValue * 60) / 1e-2d, + SpeedUnit.CentimeterPerSecond => (baseUnitValue) / 1e-2d, + SpeedUnit.DecimeterPerMinute => (baseUnitValue * 60) / 1e-1d, + SpeedUnit.DecimeterPerSecond => (baseUnitValue) / 1e-1d, + SpeedUnit.FootPerHour => baseUnitValue / 0.3048 * 3600, + SpeedUnit.FootPerMinute => baseUnitValue / 0.3048 * 60, + SpeedUnit.FootPerSecond => baseUnitValue / 0.3048, + SpeedUnit.InchPerHour => (baseUnitValue / 2.54e-2) * 3600, + SpeedUnit.InchPerMinute => (baseUnitValue / 2.54e-2) * 60, + SpeedUnit.InchPerSecond => baseUnitValue / 2.54e-2, + SpeedUnit.KilometerPerHour => (baseUnitValue * 3600) / 1e3d, + SpeedUnit.KilometerPerMinute => (baseUnitValue * 60) / 1e3d, + SpeedUnit.KilometerPerSecond => (baseUnitValue) / 1e3d, + SpeedUnit.Knot => baseUnitValue / 0.514444, + SpeedUnit.Mach => baseUnitValue / 340.29, + SpeedUnit.MeterPerHour => baseUnitValue * 3600, + SpeedUnit.MeterPerMinute => baseUnitValue * 60, + SpeedUnit.MeterPerSecond => baseUnitValue, + SpeedUnit.MicrometerPerMinute => (baseUnitValue * 60) / 1e-6d, + SpeedUnit.MicrometerPerSecond => (baseUnitValue) / 1e-6d, + SpeedUnit.MilePerHour => baseUnitValue / 0.44704, + SpeedUnit.MillimeterPerHour => (baseUnitValue * 3600) / 1e-3d, + SpeedUnit.MillimeterPerMinute => (baseUnitValue * 60) / 1e-3d, + SpeedUnit.MillimeterPerSecond => (baseUnitValue) / 1e-3d, + SpeedUnit.NanometerPerMinute => (baseUnitValue * 60) / 1e-9d, + SpeedUnit.NanometerPerSecond => (baseUnitValue) / 1e-9d, + SpeedUnit.UsSurveyFootPerHour => (baseUnitValue * 3937 / 1200) * 3600, + SpeedUnit.UsSurveyFootPerMinute => (baseUnitValue * 3937 / 1200) * 60, + SpeedUnit.UsSurveyFootPerSecond => baseUnitValue * 3937 / 1200, + SpeedUnit.YardPerHour => baseUnitValue / 0.9144 * 3600, + SpeedUnit.YardPerMinute => baseUnitValue / 0.9144 * 60, + SpeedUnit.YardPerSecond => baseUnitValue / 0.9144, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index bc5f7a486f..e127e1718a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -195,69 +195,69 @@ public static StandardVolumeFlow From(double value, StandardVolumeFlowUnit fromU #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(StandardVolumeFlowUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit) - { - var convertedValue = GetValueAs(unit); - return new StandardVolumeFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute => _value / 6e7, - StandardVolumeFlowUnit.StandardCubicFootPerHour => _value * 7.8657907199999087346816086183876e-6, - StandardVolumeFlowUnit.StandardCubicFootPerMinute => _value / 2118.88000326, - StandardVolumeFlowUnit.StandardCubicFootPerSecond => _value / 35.314666721, - StandardVolumeFlowUnit.StandardCubicMeterPerDay => _value / 86400, - StandardVolumeFlowUnit.StandardCubicMeterPerHour => _value / 3600, - StandardVolumeFlowUnit.StandardCubicMeterPerMinute => _value / 60, - StandardVolumeFlowUnit.StandardCubicMeterPerSecond => _value, - StandardVolumeFlowUnit.StandardLiterPerMinute => _value / 60000, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(StandardVolumeFlowUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute => baseUnitValue * 6e7, - StandardVolumeFlowUnit.StandardCubicFootPerHour => baseUnitValue / 7.8657907199999087346816086183876e-6, - StandardVolumeFlowUnit.StandardCubicFootPerMinute => baseUnitValue * 2118.88000326, - StandardVolumeFlowUnit.StandardCubicFootPerSecond => baseUnitValue * 35.314666721, - StandardVolumeFlowUnit.StandardCubicMeterPerDay => baseUnitValue * 86400, - StandardVolumeFlowUnit.StandardCubicMeterPerHour => baseUnitValue * 3600, - StandardVolumeFlowUnit.StandardCubicMeterPerMinute => baseUnitValue * 60, - StandardVolumeFlowUnit.StandardCubicMeterPerSecond => baseUnitValue, - StandardVolumeFlowUnit.StandardLiterPerMinute => baseUnitValue * 60000, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(StandardVolumeFlowUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit) + { + var convertedValue = GetValueAs(unit); + return new StandardVolumeFlow(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute => _value / 6e7, + StandardVolumeFlowUnit.StandardCubicFootPerHour => _value * 7.8657907199999087346816086183876e-6, + StandardVolumeFlowUnit.StandardCubicFootPerMinute => _value / 2118.88000326, + StandardVolumeFlowUnit.StandardCubicFootPerSecond => _value / 35.314666721, + StandardVolumeFlowUnit.StandardCubicMeterPerDay => _value / 86400, + StandardVolumeFlowUnit.StandardCubicMeterPerHour => _value / 3600, + StandardVolumeFlowUnit.StandardCubicMeterPerMinute => _value / 60, + StandardVolumeFlowUnit.StandardCubicMeterPerSecond => _value, + StandardVolumeFlowUnit.StandardLiterPerMinute => _value / 60000, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(StandardVolumeFlowUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute => baseUnitValue * 6e7, + StandardVolumeFlowUnit.StandardCubicFootPerHour => baseUnitValue / 7.8657907199999087346816086183876e-6, + StandardVolumeFlowUnit.StandardCubicFootPerMinute => baseUnitValue * 2118.88000326, + StandardVolumeFlowUnit.StandardCubicFootPerSecond => baseUnitValue * 35.314666721, + StandardVolumeFlowUnit.StandardCubicMeterPerDay => baseUnitValue * 86400, + StandardVolumeFlowUnit.StandardCubicMeterPerHour => baseUnitValue * 3600, + StandardVolumeFlowUnit.StandardCubicMeterPerMinute => baseUnitValue * 60, + StandardVolumeFlowUnit.StandardCubicMeterPerSecond => baseUnitValue, + StandardVolumeFlowUnit.StandardLiterPerMinute => baseUnitValue * 60000, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Temperature.g.cs index 797919359c..6488ad18ab 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Temperature.g.cs @@ -206,71 +206,71 @@ public static Temperature From(double value, TemperatureUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Temperature ToUnit(TemperatureUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Temperature(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TemperatureUnit.DegreeCelsius => _value + 273.15, - TemperatureUnit.DegreeDelisle => _value * -2 / 3 + 373.15, - TemperatureUnit.DegreeFahrenheit => _value * 5 / 9 + 459.67 * 5 / 9, - TemperatureUnit.DegreeNewton => _value * 100 / 33 + 273.15, - TemperatureUnit.DegreeRankine => _value * 5 / 9, - TemperatureUnit.DegreeReaumur => _value * 5 / 4 + 273.15, - TemperatureUnit.DegreeRoemer => _value * 40 / 21 + 273.15 - 7.5 * 40d / 21, - TemperatureUnit.Kelvin => _value, - TemperatureUnit.MillidegreeCelsius => _value / 1000 + 273.15, - TemperatureUnit.SolarTemperature => _value * 5778, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TemperatureUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TemperatureUnit.DegreeCelsius => baseUnitValue - 273.15, - TemperatureUnit.DegreeDelisle => (baseUnitValue - 373.15) * -3 / 2, - TemperatureUnit.DegreeFahrenheit => (baseUnitValue - 459.67 * 5 / 9) * 9 / 5, - TemperatureUnit.DegreeNewton => (baseUnitValue - 273.15) * 33 / 100, - TemperatureUnit.DegreeRankine => baseUnitValue * 9 / 5, - TemperatureUnit.DegreeReaumur => (baseUnitValue - 273.15) * 4 / 5, - TemperatureUnit.DegreeRoemer => (baseUnitValue - (273.15 - 7.5 * 40d / 21)) * 21 / 40, - TemperatureUnit.Kelvin => baseUnitValue, - TemperatureUnit.MillidegreeCelsius => (baseUnitValue - 273.15) * 1000, - TemperatureUnit.SolarTemperature => baseUnitValue / 5778, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Temperature ToUnit(TemperatureUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Temperature(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TemperatureUnit.DegreeCelsius => _value + 273.15, + TemperatureUnit.DegreeDelisle => _value * -2 / 3 + 373.15, + TemperatureUnit.DegreeFahrenheit => _value * 5 / 9 + 459.67 * 5 / 9, + TemperatureUnit.DegreeNewton => _value * 100 / 33 + 273.15, + TemperatureUnit.DegreeRankine => _value * 5 / 9, + TemperatureUnit.DegreeReaumur => _value * 5 / 4 + 273.15, + TemperatureUnit.DegreeRoemer => _value * 40 / 21 + 273.15 - 7.5 * 40d / 21, + TemperatureUnit.Kelvin => _value, + TemperatureUnit.MillidegreeCelsius => _value / 1000 + 273.15, + TemperatureUnit.SolarTemperature => _value * 5778, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TemperatureUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TemperatureUnit.DegreeCelsius => baseUnitValue - 273.15, + TemperatureUnit.DegreeDelisle => (baseUnitValue - 373.15) * -3 / 2, + TemperatureUnit.DegreeFahrenheit => (baseUnitValue - 459.67 * 5 / 9) * 9 / 5, + TemperatureUnit.DegreeNewton => (baseUnitValue - 273.15) * 33 / 100, + TemperatureUnit.DegreeRankine => baseUnitValue * 9 / 5, + TemperatureUnit.DegreeReaumur => (baseUnitValue - 273.15) * 4 / 5, + TemperatureUnit.DegreeRoemer => (baseUnitValue - (273.15 - 7.5 * 40d / 21)) * 21 / 40, + TemperatureUnit.Kelvin => baseUnitValue, + TemperatureUnit.MillidegreeCelsius => (baseUnitValue - 273.15) * 1000, + TemperatureUnit.SolarTemperature => baseUnitValue / 5778, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index fe6c8fc9d7..c5466171ea 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -206,71 +206,71 @@ public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureChangeRateUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) - { - var convertedValue = GetValueAs(unit); - return new TemperatureChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond => (_value) * 1e-2d, - TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond => (_value) * 1e1d, - TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond => (_value) * 1e-1d, - TemperatureChangeRateUnit.DegreeCelsiusPerMinute => _value / 60, - TemperatureChangeRateUnit.DegreeCelsiusPerSecond => _value, - TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond => (_value) * 1e2d, - TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond => (_value) * 1e3d, - TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond => (_value) * 1e-6d, - TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond => (_value) * 1e-3d, - TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond => (_value) * 1e-9d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TemperatureChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond => (baseUnitValue) / 1e-2d, - TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond => (baseUnitValue) / 1e1d, - TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond => (baseUnitValue) / 1e-1d, - TemperatureChangeRateUnit.DegreeCelsiusPerMinute => baseUnitValue * 60, - TemperatureChangeRateUnit.DegreeCelsiusPerSecond => baseUnitValue, - TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond => (baseUnitValue) / 1e2d, - TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond => (baseUnitValue) / 1e3d, - TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond => (baseUnitValue) / 1e-6d, - TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond => (baseUnitValue) / 1e-3d, - TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond => (baseUnitValue) / 1e-9d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureChangeRateUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) + { + var convertedValue = GetValueAs(unit); + return new TemperatureChangeRate(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond => (_value) * 1e-2d, + TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond => (_value) * 1e1d, + TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond => (_value) * 1e-1d, + TemperatureChangeRateUnit.DegreeCelsiusPerMinute => _value / 60, + TemperatureChangeRateUnit.DegreeCelsiusPerSecond => _value, + TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond => (_value) * 1e2d, + TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond => (_value) * 1e3d, + TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond => (_value) * 1e-6d, + TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond => (_value) * 1e-3d, + TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond => (_value) * 1e-9d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TemperatureChangeRateUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond => (baseUnitValue) / 1e-2d, + TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond => (baseUnitValue) / 1e1d, + TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond => (baseUnitValue) / 1e-1d, + TemperatureChangeRateUnit.DegreeCelsiusPerMinute => baseUnitValue * 60, + TemperatureChangeRateUnit.DegreeCelsiusPerSecond => baseUnitValue, + TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond => (baseUnitValue) / 1e2d, + TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond => (baseUnitValue) / 1e3d, + TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond => (baseUnitValue) / 1e-6d, + TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond => (baseUnitValue) / 1e-3d, + TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond => (baseUnitValue) / 1e-9d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureDelta.g.cs index 272d1603e5..2f3ce6d3cf 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -195,69 +195,69 @@ public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureDeltaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new TemperatureDelta(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TemperatureDeltaUnit.DegreeCelsius => _value, - TemperatureDeltaUnit.DegreeDelisle => _value * -2 / 3, - TemperatureDeltaUnit.DegreeFahrenheit => _value * 5 / 9, - TemperatureDeltaUnit.DegreeNewton => _value * 100 / 33, - TemperatureDeltaUnit.DegreeRankine => _value * 5 / 9, - TemperatureDeltaUnit.DegreeReaumur => _value * 5 / 4, - TemperatureDeltaUnit.DegreeRoemer => _value * 40 / 21, - TemperatureDeltaUnit.Kelvin => _value, - TemperatureDeltaUnit.MillidegreeCelsius => (_value) * 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TemperatureDeltaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TemperatureDeltaUnit.DegreeCelsius => baseUnitValue, - TemperatureDeltaUnit.DegreeDelisle => baseUnitValue * -3 / 2, - TemperatureDeltaUnit.DegreeFahrenheit => baseUnitValue * 9 / 5, - TemperatureDeltaUnit.DegreeNewton => baseUnitValue * 33 / 100, - TemperatureDeltaUnit.DegreeRankine => baseUnitValue * 9 / 5, - TemperatureDeltaUnit.DegreeReaumur => baseUnitValue * 4 / 5, - TemperatureDeltaUnit.DegreeRoemer => baseUnitValue * 21 / 40, - TemperatureDeltaUnit.Kelvin => baseUnitValue, - TemperatureDeltaUnit.MillidegreeCelsius => (baseUnitValue) / 1e-3d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureDeltaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new TemperatureDelta(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TemperatureDeltaUnit.DegreeCelsius => _value, + TemperatureDeltaUnit.DegreeDelisle => _value * -2 / 3, + TemperatureDeltaUnit.DegreeFahrenheit => _value * 5 / 9, + TemperatureDeltaUnit.DegreeNewton => _value * 100 / 33, + TemperatureDeltaUnit.DegreeRankine => _value * 5 / 9, + TemperatureDeltaUnit.DegreeReaumur => _value * 5 / 4, + TemperatureDeltaUnit.DegreeRoemer => _value * 40 / 21, + TemperatureDeltaUnit.Kelvin => _value, + TemperatureDeltaUnit.MillidegreeCelsius => (_value) * 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TemperatureDeltaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TemperatureDeltaUnit.DegreeCelsius => baseUnitValue, + TemperatureDeltaUnit.DegreeDelisle => baseUnitValue * -3 / 2, + TemperatureDeltaUnit.DegreeFahrenheit => baseUnitValue * 9 / 5, + TemperatureDeltaUnit.DegreeNewton => baseUnitValue * 33 / 100, + TemperatureDeltaUnit.DegreeRankine => baseUnitValue * 9 / 5, + TemperatureDeltaUnit.DegreeReaumur => baseUnitValue * 4 / 5, + TemperatureDeltaUnit.DegreeRoemer => baseUnitValue * 21 / 40, + TemperatureDeltaUnit.Kelvin => baseUnitValue, + TemperatureDeltaUnit.MillidegreeCelsius => (baseUnitValue) / 1e-3d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureGradient.g.cs index b6b42c7d16..2f2283f3af 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// The rate of change of temperature with displacement in a given direction (as with increase of height) + /// /// public struct TemperatureGradient { @@ -140,59 +140,59 @@ public static TemperatureGradient From(double value, TemperatureGradientUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureGradientUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public TemperatureGradient ToUnit(TemperatureGradientUnit unit) - { - var convertedValue = GetValueAs(unit); - return new TemperatureGradient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TemperatureGradientUnit.DegreeCelsiusPerKilometer => _value / 1e3, - TemperatureGradientUnit.DegreeCelsiusPerMeter => _value, - TemperatureGradientUnit.DegreeFahrenheitPerFoot => (_value / 0.3048) * 5 / 9, - TemperatureGradientUnit.KelvinPerMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TemperatureGradientUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TemperatureGradientUnit.DegreeCelsiusPerKilometer => baseUnitValue * 1e3, - TemperatureGradientUnit.DegreeCelsiusPerMeter => baseUnitValue, - TemperatureGradientUnit.DegreeFahrenheitPerFoot => (baseUnitValue * 0.3048) * 9 / 5, - TemperatureGradientUnit.KelvinPerMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TemperatureGradientUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public TemperatureGradient ToUnit(TemperatureGradientUnit unit) + { + var convertedValue = GetValueAs(unit); + return new TemperatureGradient(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TemperatureGradientUnit.DegreeCelsiusPerKilometer => _value / 1e3, + TemperatureGradientUnit.DegreeCelsiusPerMeter => _value, + TemperatureGradientUnit.DegreeFahrenheitPerFoot => (_value / 0.3048) * 5 / 9, + TemperatureGradientUnit.KelvinPerMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TemperatureGradientUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TemperatureGradientUnit.DegreeCelsiusPerKilometer => baseUnitValue * 1e3, + TemperatureGradientUnit.DegreeCelsiusPerMeter => baseUnitValue, + TemperatureGradientUnit.DegreeFahrenheitPerFoot => (baseUnitValue * 0.3048) * 9 / 5, + TemperatureGradientUnit.KelvinPerMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalConductivity.g.cs index e80a48512e..a462e9387d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -121,55 +121,55 @@ public static ThermalConductivity From(double value, ThermalConductivityUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalConductivityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ThermalConductivity ToUnit(ThermalConductivityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ThermalConductivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ThermalConductivityUnit.BtuPerHourFootFahrenheit => _value * 1.73073467, - ThermalConductivityUnit.WattPerMeterKelvin => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ThermalConductivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ThermalConductivityUnit.BtuPerHourFootFahrenheit => baseUnitValue / 1.73073467, - ThermalConductivityUnit.WattPerMeterKelvin => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ThermalConductivityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ThermalConductivity ToUnit(ThermalConductivityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ThermalConductivity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ThermalConductivityUnit.BtuPerHourFootFahrenheit => _value * 1.73073467, + ThermalConductivityUnit.WattPerMeterKelvin => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ThermalConductivityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ThermalConductivityUnit.BtuPerHourFootFahrenheit => baseUnitValue / 1.73073467, + ThermalConductivityUnit.WattPerMeterKelvin => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalResistance.g.cs index 2789664ffa..3acf38bab5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -162,63 +162,63 @@ public static ThermalResistance From(double value, ThermalResistanceUnit fromUni #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalResistanceUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public ThermalResistance ToUnit(ThermalResistanceUnit unit) - { - var convertedValue = GetValueAs(unit); - return new ThermalResistance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu => _value * 176.1121482159839, - ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie => _value * 0.0859779507590433, - ThermalResistanceUnit.SquareCentimeterKelvinPerWatt => _value * 0.1, - ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt => _value * 1000.0, - ThermalResistanceUnit.SquareMeterKelvinPerKilowatt => _value, - ThermalResistanceUnit.SquareMeterKelvinPerWatt => _value * 1000, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(ThermalResistanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu => baseUnitValue / 176.1121482159839, - ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie => baseUnitValue / 0.0859779507590433, - ThermalResistanceUnit.SquareCentimeterKelvinPerWatt => baseUnitValue / 0.1, - ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt => baseUnitValue / 1000.0, - ThermalResistanceUnit.SquareMeterKelvinPerKilowatt => baseUnitValue, - ThermalResistanceUnit.SquareMeterKelvinPerWatt => baseUnitValue / 1000, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(ThermalResistanceUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public ThermalResistance ToUnit(ThermalResistanceUnit unit) + { + var convertedValue = GetValueAs(unit); + return new ThermalResistance(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu => _value * 176.1121482159839, + ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie => _value * 0.0859779507590433, + ThermalResistanceUnit.SquareCentimeterKelvinPerWatt => _value * 0.1, + ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt => _value * 1000.0, + ThermalResistanceUnit.SquareMeterKelvinPerKilowatt => _value, + ThermalResistanceUnit.SquareMeterKelvinPerWatt => _value * 1000, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(ThermalResistanceUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu => baseUnitValue / 176.1121482159839, + ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie => baseUnitValue / 0.0859779507590433, + ThermalResistanceUnit.SquareCentimeterKelvinPerWatt => baseUnitValue / 0.1, + ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt => baseUnitValue / 1000.0, + ThermalResistanceUnit.SquareMeterKelvinPerKilowatt => baseUnitValue, + ThermalResistanceUnit.SquareMeterKelvinPerWatt => baseUnitValue / 1000, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Torque.g.cs index a73aab1438..1f0bb062c1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Torque.g.cs @@ -371,101 +371,101 @@ public static Torque From(double value, TorqueUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorqueUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Torque ToUnit(TorqueUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Torque(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TorqueUnit.GramForceCentimeter => _value * 9.80665e-5, - TorqueUnit.GramForceMeter => _value * 9.80665e-3, - TorqueUnit.GramForceMillimeter => _value * 9.80665e-6, - TorqueUnit.KilogramForceCentimeter => _value * 9.80665e-2, - TorqueUnit.KilogramForceMeter => _value * 9.80665, - TorqueUnit.KilogramForceMillimeter => _value * 9.80665e-3, - TorqueUnit.KilonewtonCentimeter => (_value * 0.01) * 1e3d, - TorqueUnit.KilonewtonMeter => (_value) * 1e3d, - TorqueUnit.KilonewtonMillimeter => (_value * 0.001) * 1e3d, - TorqueUnit.KilopoundForceFoot => (_value * 1.3558179483314) * 1e3d, - TorqueUnit.KilopoundForceInch => (_value * 1.129848290276167e-1) * 1e3d, - TorqueUnit.MeganewtonCentimeter => (_value * 0.01) * 1e6d, - TorqueUnit.MeganewtonMeter => (_value) * 1e6d, - TorqueUnit.MeganewtonMillimeter => (_value * 0.001) * 1e6d, - TorqueUnit.MegapoundForceFoot => (_value * 1.3558179483314) * 1e6d, - TorqueUnit.MegapoundForceInch => (_value * 1.129848290276167e-1) * 1e6d, - TorqueUnit.NewtonCentimeter => _value * 0.01, - TorqueUnit.NewtonMeter => _value, - TorqueUnit.NewtonMillimeter => _value * 0.001, - TorqueUnit.PoundalFoot => _value * 4.21401100938048e-2, - TorqueUnit.PoundForceFoot => _value * 1.3558179483314, - TorqueUnit.PoundForceInch => _value * 1.129848290276167e-1, - TorqueUnit.TonneForceCentimeter => _value * 9.80665e1, - TorqueUnit.TonneForceMeter => _value * 9.80665e3, - TorqueUnit.TonneForceMillimeter => _value * 9.80665, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TorqueUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TorqueUnit.GramForceCentimeter => baseUnitValue / 9.80665e-5, - TorqueUnit.GramForceMeter => baseUnitValue / 9.80665e-3, - TorqueUnit.GramForceMillimeter => baseUnitValue / 9.80665e-6, - TorqueUnit.KilogramForceCentimeter => baseUnitValue / 9.80665e-2, - TorqueUnit.KilogramForceMeter => baseUnitValue / 9.80665, - TorqueUnit.KilogramForceMillimeter => baseUnitValue / 9.80665e-3, - TorqueUnit.KilonewtonCentimeter => (baseUnitValue * 100) / 1e3d, - TorqueUnit.KilonewtonMeter => (baseUnitValue) / 1e3d, - TorqueUnit.KilonewtonMillimeter => (baseUnitValue * 1000) / 1e3d, - TorqueUnit.KilopoundForceFoot => (baseUnitValue / 1.3558179483314) / 1e3d, - TorqueUnit.KilopoundForceInch => (baseUnitValue / 1.129848290276167e-1) / 1e3d, - TorqueUnit.MeganewtonCentimeter => (baseUnitValue * 100) / 1e6d, - TorqueUnit.MeganewtonMeter => (baseUnitValue) / 1e6d, - TorqueUnit.MeganewtonMillimeter => (baseUnitValue * 1000) / 1e6d, - TorqueUnit.MegapoundForceFoot => (baseUnitValue / 1.3558179483314) / 1e6d, - TorqueUnit.MegapoundForceInch => (baseUnitValue / 1.129848290276167e-1) / 1e6d, - TorqueUnit.NewtonCentimeter => baseUnitValue * 100, - TorqueUnit.NewtonMeter => baseUnitValue, - TorqueUnit.NewtonMillimeter => baseUnitValue * 1000, - TorqueUnit.PoundalFoot => baseUnitValue / 4.21401100938048e-2, - TorqueUnit.PoundForceFoot => baseUnitValue / 1.3558179483314, - TorqueUnit.PoundForceInch => baseUnitValue / 1.129848290276167e-1, - TorqueUnit.TonneForceCentimeter => baseUnitValue / 9.80665e1, - TorqueUnit.TonneForceMeter => baseUnitValue / 9.80665e3, - TorqueUnit.TonneForceMillimeter => baseUnitValue / 9.80665, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TorqueUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Torque ToUnit(TorqueUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Torque(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TorqueUnit.GramForceCentimeter => _value * 9.80665e-5, + TorqueUnit.GramForceMeter => _value * 9.80665e-3, + TorqueUnit.GramForceMillimeter => _value * 9.80665e-6, + TorqueUnit.KilogramForceCentimeter => _value * 9.80665e-2, + TorqueUnit.KilogramForceMeter => _value * 9.80665, + TorqueUnit.KilogramForceMillimeter => _value * 9.80665e-3, + TorqueUnit.KilonewtonCentimeter => (_value * 0.01) * 1e3d, + TorqueUnit.KilonewtonMeter => (_value) * 1e3d, + TorqueUnit.KilonewtonMillimeter => (_value * 0.001) * 1e3d, + TorqueUnit.KilopoundForceFoot => (_value * 1.3558179483314) * 1e3d, + TorqueUnit.KilopoundForceInch => (_value * 1.129848290276167e-1) * 1e3d, + TorqueUnit.MeganewtonCentimeter => (_value * 0.01) * 1e6d, + TorqueUnit.MeganewtonMeter => (_value) * 1e6d, + TorqueUnit.MeganewtonMillimeter => (_value * 0.001) * 1e6d, + TorqueUnit.MegapoundForceFoot => (_value * 1.3558179483314) * 1e6d, + TorqueUnit.MegapoundForceInch => (_value * 1.129848290276167e-1) * 1e6d, + TorqueUnit.NewtonCentimeter => _value * 0.01, + TorqueUnit.NewtonMeter => _value, + TorqueUnit.NewtonMillimeter => _value * 0.001, + TorqueUnit.PoundalFoot => _value * 4.21401100938048e-2, + TorqueUnit.PoundForceFoot => _value * 1.3558179483314, + TorqueUnit.PoundForceInch => _value * 1.129848290276167e-1, + TorqueUnit.TonneForceCentimeter => _value * 9.80665e1, + TorqueUnit.TonneForceMeter => _value * 9.80665e3, + TorqueUnit.TonneForceMillimeter => _value * 9.80665, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TorqueUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TorqueUnit.GramForceCentimeter => baseUnitValue / 9.80665e-5, + TorqueUnit.GramForceMeter => baseUnitValue / 9.80665e-3, + TorqueUnit.GramForceMillimeter => baseUnitValue / 9.80665e-6, + TorqueUnit.KilogramForceCentimeter => baseUnitValue / 9.80665e-2, + TorqueUnit.KilogramForceMeter => baseUnitValue / 9.80665, + TorqueUnit.KilogramForceMillimeter => baseUnitValue / 9.80665e-3, + TorqueUnit.KilonewtonCentimeter => (baseUnitValue * 100) / 1e3d, + TorqueUnit.KilonewtonMeter => (baseUnitValue) / 1e3d, + TorqueUnit.KilonewtonMillimeter => (baseUnitValue * 1000) / 1e3d, + TorqueUnit.KilopoundForceFoot => (baseUnitValue / 1.3558179483314) / 1e3d, + TorqueUnit.KilopoundForceInch => (baseUnitValue / 1.129848290276167e-1) / 1e3d, + TorqueUnit.MeganewtonCentimeter => (baseUnitValue * 100) / 1e6d, + TorqueUnit.MeganewtonMeter => (baseUnitValue) / 1e6d, + TorqueUnit.MeganewtonMillimeter => (baseUnitValue * 1000) / 1e6d, + TorqueUnit.MegapoundForceFoot => (baseUnitValue / 1.3558179483314) / 1e6d, + TorqueUnit.MegapoundForceInch => (baseUnitValue / 1.129848290276167e-1) / 1e6d, + TorqueUnit.NewtonCentimeter => baseUnitValue * 100, + TorqueUnit.NewtonMeter => baseUnitValue, + TorqueUnit.NewtonMillimeter => baseUnitValue * 1000, + TorqueUnit.PoundalFoot => baseUnitValue / 4.21401100938048e-2, + TorqueUnit.PoundForceFoot => baseUnitValue / 1.3558179483314, + TorqueUnit.PoundForceInch => baseUnitValue / 1.129848290276167e-1, + TorqueUnit.TonneForceCentimeter => baseUnitValue / 9.80665e1, + TorqueUnit.TonneForceMeter => baseUnitValue / 9.80665e3, + TorqueUnit.TonneForceMillimeter => baseUnitValue / 9.80665, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TorquePerLength.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TorquePerLength.g.cs index 78eddade11..34e9304251 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/TorquePerLength.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/TorquePerLength.g.cs @@ -327,93 +327,93 @@ public static TorquePerLength From(double value, TorquePerLengthUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorquePerLengthUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public TorquePerLength ToUnit(TorquePerLengthUnit unit) - { - var convertedValue = GetValueAs(unit); - return new TorquePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TorquePerLengthUnit.KilogramForceCentimeterPerMeter => _value * 0.0980665019960652, - TorquePerLengthUnit.KilogramForceMeterPerMeter => _value * 9.80665019960652, - TorquePerLengthUnit.KilogramForceMillimeterPerMeter => _value * 0.00980665019960652, - TorquePerLengthUnit.KilonewtonCentimeterPerMeter => (_value * 0.01) * 1e3d, - TorquePerLengthUnit.KilonewtonMeterPerMeter => (_value) * 1e3d, - TorquePerLengthUnit.KilonewtonMillimeterPerMeter => (_value * 0.001) * 1e3d, - TorquePerLengthUnit.KilopoundForceFootPerFoot => (_value * 4.44822161526) * 1e3d, - TorquePerLengthUnit.KilopoundForceInchPerFoot => (_value * 0.370685147638) * 1e3d, - TorquePerLengthUnit.MeganewtonCentimeterPerMeter => (_value * 0.01) * 1e6d, - TorquePerLengthUnit.MeganewtonMeterPerMeter => (_value) * 1e6d, - TorquePerLengthUnit.MeganewtonMillimeterPerMeter => (_value * 0.001) * 1e6d, - TorquePerLengthUnit.MegapoundForceFootPerFoot => (_value * 4.44822161526) * 1e6d, - TorquePerLengthUnit.MegapoundForceInchPerFoot => (_value * 0.370685147638) * 1e6d, - TorquePerLengthUnit.NewtonCentimeterPerMeter => _value * 0.01, - TorquePerLengthUnit.NewtonMeterPerMeter => _value, - TorquePerLengthUnit.NewtonMillimeterPerMeter => _value * 0.001, - TorquePerLengthUnit.PoundForceFootPerFoot => _value * 4.44822161526, - TorquePerLengthUnit.PoundForceInchPerFoot => _value * 0.370685147638, - TorquePerLengthUnit.TonneForceCentimeterPerMeter => _value * 98.0665019960652, - TorquePerLengthUnit.TonneForceMeterPerMeter => _value * 9806.65019960653, - TorquePerLengthUnit.TonneForceMillimeterPerMeter => _value * 9.80665019960652, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TorquePerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TorquePerLengthUnit.KilogramForceCentimeterPerMeter => baseUnitValue * 10.1971619222242, - TorquePerLengthUnit.KilogramForceMeterPerMeter => baseUnitValue * 0.101971619222242, - TorquePerLengthUnit.KilogramForceMillimeterPerMeter => baseUnitValue * 101.971619222242, - TorquePerLengthUnit.KilonewtonCentimeterPerMeter => (baseUnitValue * 100) / 1e3d, - TorquePerLengthUnit.KilonewtonMeterPerMeter => (baseUnitValue) / 1e3d, - TorquePerLengthUnit.KilonewtonMillimeterPerMeter => (baseUnitValue * 1000) / 1e3d, - TorquePerLengthUnit.KilopoundForceFootPerFoot => (baseUnitValue / 4.44822161526) / 1e3d, - TorquePerLengthUnit.KilopoundForceInchPerFoot => (baseUnitValue / 0.370685147638) / 1e3d, - TorquePerLengthUnit.MeganewtonCentimeterPerMeter => (baseUnitValue * 100) / 1e6d, - TorquePerLengthUnit.MeganewtonMeterPerMeter => (baseUnitValue) / 1e6d, - TorquePerLengthUnit.MeganewtonMillimeterPerMeter => (baseUnitValue * 1000) / 1e6d, - TorquePerLengthUnit.MegapoundForceFootPerFoot => (baseUnitValue / 4.44822161526) / 1e6d, - TorquePerLengthUnit.MegapoundForceInchPerFoot => (baseUnitValue / 0.370685147638) / 1e6d, - TorquePerLengthUnit.NewtonCentimeterPerMeter => baseUnitValue * 100, - TorquePerLengthUnit.NewtonMeterPerMeter => baseUnitValue, - TorquePerLengthUnit.NewtonMillimeterPerMeter => baseUnitValue * 1000, - TorquePerLengthUnit.PoundForceFootPerFoot => baseUnitValue / 4.44822161526, - TorquePerLengthUnit.PoundForceInchPerFoot => baseUnitValue / 0.370685147638, - TorquePerLengthUnit.TonneForceCentimeterPerMeter => baseUnitValue * 0.0101971619222242, - TorquePerLengthUnit.TonneForceMeterPerMeter => baseUnitValue * 0.000101971619222242, - TorquePerLengthUnit.TonneForceMillimeterPerMeter => baseUnitValue * 0.101971619222242, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TorquePerLengthUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public TorquePerLength ToUnit(TorquePerLengthUnit unit) + { + var convertedValue = GetValueAs(unit); + return new TorquePerLength(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TorquePerLengthUnit.KilogramForceCentimeterPerMeter => _value * 0.0980665019960652, + TorquePerLengthUnit.KilogramForceMeterPerMeter => _value * 9.80665019960652, + TorquePerLengthUnit.KilogramForceMillimeterPerMeter => _value * 0.00980665019960652, + TorquePerLengthUnit.KilonewtonCentimeterPerMeter => (_value * 0.01) * 1e3d, + TorquePerLengthUnit.KilonewtonMeterPerMeter => (_value) * 1e3d, + TorquePerLengthUnit.KilonewtonMillimeterPerMeter => (_value * 0.001) * 1e3d, + TorquePerLengthUnit.KilopoundForceFootPerFoot => (_value * 4.44822161526) * 1e3d, + TorquePerLengthUnit.KilopoundForceInchPerFoot => (_value * 0.370685147638) * 1e3d, + TorquePerLengthUnit.MeganewtonCentimeterPerMeter => (_value * 0.01) * 1e6d, + TorquePerLengthUnit.MeganewtonMeterPerMeter => (_value) * 1e6d, + TorquePerLengthUnit.MeganewtonMillimeterPerMeter => (_value * 0.001) * 1e6d, + TorquePerLengthUnit.MegapoundForceFootPerFoot => (_value * 4.44822161526) * 1e6d, + TorquePerLengthUnit.MegapoundForceInchPerFoot => (_value * 0.370685147638) * 1e6d, + TorquePerLengthUnit.NewtonCentimeterPerMeter => _value * 0.01, + TorquePerLengthUnit.NewtonMeterPerMeter => _value, + TorquePerLengthUnit.NewtonMillimeterPerMeter => _value * 0.001, + TorquePerLengthUnit.PoundForceFootPerFoot => _value * 4.44822161526, + TorquePerLengthUnit.PoundForceInchPerFoot => _value * 0.370685147638, + TorquePerLengthUnit.TonneForceCentimeterPerMeter => _value * 98.0665019960652, + TorquePerLengthUnit.TonneForceMeterPerMeter => _value * 9806.65019960653, + TorquePerLengthUnit.TonneForceMillimeterPerMeter => _value * 9.80665019960652, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TorquePerLengthUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TorquePerLengthUnit.KilogramForceCentimeterPerMeter => baseUnitValue * 10.1971619222242, + TorquePerLengthUnit.KilogramForceMeterPerMeter => baseUnitValue * 0.101971619222242, + TorquePerLengthUnit.KilogramForceMillimeterPerMeter => baseUnitValue * 101.971619222242, + TorquePerLengthUnit.KilonewtonCentimeterPerMeter => (baseUnitValue * 100) / 1e3d, + TorquePerLengthUnit.KilonewtonMeterPerMeter => (baseUnitValue) / 1e3d, + TorquePerLengthUnit.KilonewtonMillimeterPerMeter => (baseUnitValue * 1000) / 1e3d, + TorquePerLengthUnit.KilopoundForceFootPerFoot => (baseUnitValue / 4.44822161526) / 1e3d, + TorquePerLengthUnit.KilopoundForceInchPerFoot => (baseUnitValue / 0.370685147638) / 1e3d, + TorquePerLengthUnit.MeganewtonCentimeterPerMeter => (baseUnitValue * 100) / 1e6d, + TorquePerLengthUnit.MeganewtonMeterPerMeter => (baseUnitValue) / 1e6d, + TorquePerLengthUnit.MeganewtonMillimeterPerMeter => (baseUnitValue * 1000) / 1e6d, + TorquePerLengthUnit.MegapoundForceFootPerFoot => (baseUnitValue / 4.44822161526) / 1e6d, + TorquePerLengthUnit.MegapoundForceInchPerFoot => (baseUnitValue / 0.370685147638) / 1e6d, + TorquePerLengthUnit.NewtonCentimeterPerMeter => baseUnitValue * 100, + TorquePerLengthUnit.NewtonMeterPerMeter => baseUnitValue, + TorquePerLengthUnit.NewtonMillimeterPerMeter => baseUnitValue * 1000, + TorquePerLengthUnit.PoundForceFootPerFoot => baseUnitValue / 4.44822161526, + TorquePerLengthUnit.PoundForceInchPerFoot => baseUnitValue / 0.370685147638, + TorquePerLengthUnit.TonneForceCentimeterPerMeter => baseUnitValue * 0.0101971619222242, + TorquePerLengthUnit.TonneForceMeterPerMeter => baseUnitValue * 0.000101971619222242, + TorquePerLengthUnit.TonneForceMillimeterPerMeter => baseUnitValue * 0.101971619222242, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Turbidity.g.cs index be719ab233..d488e95ea3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Turbidity.g.cs @@ -110,53 +110,53 @@ public static Turbidity From(double value, TurbidityUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TurbidityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Turbidity ToUnit(TurbidityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Turbidity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - TurbidityUnit.NTU => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(TurbidityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - TurbidityUnit.NTU => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(TurbidityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Turbidity ToUnit(TurbidityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Turbidity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + TurbidityUnit.NTU => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(TurbidityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + TurbidityUnit.NTU => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VitaminA.g.cs index 256f98b059..12691f1a73 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VitaminA.g.cs @@ -107,53 +107,53 @@ public static VitaminA From(double value, VitaminAUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VitaminAUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public VitaminA ToUnit(VitaminAUnit unit) - { - var convertedValue = GetValueAs(unit); - return new VitaminA(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VitaminAUnit.InternationalUnit => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VitaminAUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VitaminAUnit.InternationalUnit => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VitaminAUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public VitaminA ToUnit(VitaminAUnit unit) + { + var convertedValue = GetValueAs(unit); + return new VitaminA(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VitaminAUnit.InternationalUnit => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VitaminAUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VitaminAUnit.InternationalUnit => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Volume.g.cs index 4de89abbc1..434e81acc1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Volume.g.cs @@ -668,155 +668,155 @@ public static Volume From(double value, VolumeUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Volume ToUnit(VolumeUnit unit) - { - var convertedValue = GetValueAs(unit); - return new Volume(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VolumeUnit.AcreFoot => _value / 0.000810714, - VolumeUnit.AuTablespoon => _value * 2e-5, - VolumeUnit.BoardFoot => _value * 2.3597372158e-3, - VolumeUnit.Centiliter => (_value / 1e3) * 1e-2d, - VolumeUnit.CubicCentimeter => _value / 1e6, - VolumeUnit.CubicDecimeter => _value / 1e3, - VolumeUnit.CubicFoot => _value * 2.8316846592e-2, - VolumeUnit.CubicHectometer => _value * 1e6, - VolumeUnit.CubicInch => _value * 1.6387 * 1e-5, - VolumeUnit.CubicKilometer => _value * 1e9, - VolumeUnit.CubicMeter => _value, - VolumeUnit.CubicMicrometer => _value / 1e18, - VolumeUnit.CubicMile => _value * 4.16818182544058e9, - VolumeUnit.CubicMillimeter => _value / 1e9, - VolumeUnit.CubicYard => _value * 0.764554858, - VolumeUnit.Decaliter => (_value / 1e3) * 1e1d, - VolumeUnit.DecausGallon => (_value * 0.00378541) * 1e1d, - VolumeUnit.Deciliter => (_value / 1e3) * 1e-1d, - VolumeUnit.DeciusGallon => (_value * 0.00378541) * 1e-1d, - VolumeUnit.HectocubicFoot => (_value * 2.8316846592e-2) * 1e2d, - VolumeUnit.HectocubicMeter => (_value) * 1e2d, - VolumeUnit.Hectoliter => (_value / 1e3) * 1e2d, - VolumeUnit.HectousGallon => (_value * 0.00378541) * 1e2d, - VolumeUnit.ImperialBeerBarrel => _value * 0.16365924, - VolumeUnit.ImperialGallon => _value * 0.00454609000000181429905810072407, - VolumeUnit.ImperialOunce => _value * 2.8413062499962901241875439064617e-5, - VolumeUnit.ImperialPint => _value * 5.6826125e-4, - VolumeUnit.KilocubicFoot => (_value * 2.8316846592e-2) * 1e3d, - VolumeUnit.KilocubicMeter => (_value) * 1e3d, - VolumeUnit.KiloimperialGallon => (_value * 0.00454609000000181429905810072407) * 1e3d, - VolumeUnit.Kiloliter => (_value / 1e3) * 1e3d, - VolumeUnit.KilousGallon => (_value * 0.00378541) * 1e3d, - VolumeUnit.Liter => _value / 1e3, - VolumeUnit.MegacubicFoot => (_value * 2.8316846592e-2) * 1e6d, - VolumeUnit.MegaimperialGallon => (_value * 0.00454609000000181429905810072407) * 1e6d, - VolumeUnit.Megaliter => (_value / 1e3) * 1e6d, - VolumeUnit.MegausGallon => (_value * 0.00378541) * 1e6d, - VolumeUnit.MetricCup => _value * 0.00025, - VolumeUnit.MetricTeaspoon => _value * 0.5e-5, - VolumeUnit.Microliter => (_value / 1e3) * 1e-6d, - VolumeUnit.Milliliter => (_value / 1e3) * 1e-3d, - VolumeUnit.OilBarrel => _value * 0.158987294928, - VolumeUnit.UkTablespoon => _value * 1.5e-5, - VolumeUnit.UsBeerBarrel => _value * 0.1173477658, - VolumeUnit.UsCustomaryCup => _value * 0.0002365882365, - VolumeUnit.UsGallon => _value * 0.00378541, - VolumeUnit.UsLegalCup => _value * 0.00024, - VolumeUnit.UsOunce => _value * 2.957352956253760505068307980135e-5, - VolumeUnit.UsPint => _value * 4.73176473e-4, - VolumeUnit.UsQuart => _value * 9.46352946e-4, - VolumeUnit.UsTablespoon => _value * 1.478676478125e-5, - VolumeUnit.UsTeaspoon => _value * 4.92892159375e-6, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VolumeUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VolumeUnit.AcreFoot => baseUnitValue * 0.000810714, - VolumeUnit.AuTablespoon => baseUnitValue / 2e-5, - VolumeUnit.BoardFoot => baseUnitValue / 2.3597372158e-3, - VolumeUnit.Centiliter => (baseUnitValue * 1e3) / 1e-2d, - VolumeUnit.CubicCentimeter => baseUnitValue * 1e6, - VolumeUnit.CubicDecimeter => baseUnitValue * 1e3, - VolumeUnit.CubicFoot => baseUnitValue / 2.8316846592e-2, - VolumeUnit.CubicHectometer => baseUnitValue / 1e6, - VolumeUnit.CubicInch => baseUnitValue / (1.6387 * 1e-5), - VolumeUnit.CubicKilometer => baseUnitValue / 1e9, - VolumeUnit.CubicMeter => baseUnitValue, - VolumeUnit.CubicMicrometer => baseUnitValue * 1e18, - VolumeUnit.CubicMile => baseUnitValue / 4.16818182544058e9, - VolumeUnit.CubicMillimeter => baseUnitValue * 1e9, - VolumeUnit.CubicYard => baseUnitValue / 0.764554858, - VolumeUnit.Decaliter => (baseUnitValue * 1e3) / 1e1d, - VolumeUnit.DecausGallon => (baseUnitValue / 0.00378541) / 1e1d, - VolumeUnit.Deciliter => (baseUnitValue * 1e3) / 1e-1d, - VolumeUnit.DeciusGallon => (baseUnitValue / 0.00378541) / 1e-1d, - VolumeUnit.HectocubicFoot => (baseUnitValue / 2.8316846592e-2) / 1e2d, - VolumeUnit.HectocubicMeter => (baseUnitValue) / 1e2d, - VolumeUnit.Hectoliter => (baseUnitValue * 1e3) / 1e2d, - VolumeUnit.HectousGallon => (baseUnitValue / 0.00378541) / 1e2d, - VolumeUnit.ImperialBeerBarrel => baseUnitValue / 0.16365924, - VolumeUnit.ImperialGallon => baseUnitValue / 0.00454609000000181429905810072407, - VolumeUnit.ImperialOunce => baseUnitValue / 2.8413062499962901241875439064617e-5, - VolumeUnit.ImperialPint => baseUnitValue / 5.6826125e-4, - VolumeUnit.KilocubicFoot => (baseUnitValue / 2.8316846592e-2) / 1e3d, - VolumeUnit.KilocubicMeter => (baseUnitValue) / 1e3d, - VolumeUnit.KiloimperialGallon => (baseUnitValue / 0.00454609000000181429905810072407) / 1e3d, - VolumeUnit.Kiloliter => (baseUnitValue * 1e3) / 1e3d, - VolumeUnit.KilousGallon => (baseUnitValue / 0.00378541) / 1e3d, - VolumeUnit.Liter => baseUnitValue * 1e3, - VolumeUnit.MegacubicFoot => (baseUnitValue / 2.8316846592e-2) / 1e6d, - VolumeUnit.MegaimperialGallon => (baseUnitValue / 0.00454609000000181429905810072407) / 1e6d, - VolumeUnit.Megaliter => (baseUnitValue * 1e3) / 1e6d, - VolumeUnit.MegausGallon => (baseUnitValue / 0.00378541) / 1e6d, - VolumeUnit.MetricCup => baseUnitValue / 0.00025, - VolumeUnit.MetricTeaspoon => baseUnitValue / 0.5e-5, - VolumeUnit.Microliter => (baseUnitValue * 1e3) / 1e-6d, - VolumeUnit.Milliliter => (baseUnitValue * 1e3) / 1e-3d, - VolumeUnit.OilBarrel => baseUnitValue / 0.158987294928, - VolumeUnit.UkTablespoon => baseUnitValue / 1.5e-5, - VolumeUnit.UsBeerBarrel => baseUnitValue / 0.1173477658, - VolumeUnit.UsCustomaryCup => baseUnitValue / 0.0002365882365, - VolumeUnit.UsGallon => baseUnitValue / 0.00378541, - VolumeUnit.UsLegalCup => baseUnitValue / 0.00024, - VolumeUnit.UsOunce => baseUnitValue / 2.957352956253760505068307980135e-5, - VolumeUnit.UsPint => baseUnitValue / 4.73176473e-4, - VolumeUnit.UsQuart => baseUnitValue / 9.46352946e-4, - VolumeUnit.UsTablespoon => baseUnitValue / 1.478676478125e-5, - VolumeUnit.UsTeaspoon => baseUnitValue / 4.92892159375e-6, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public Volume ToUnit(VolumeUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Volume(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VolumeUnit.AcreFoot => _value / 0.000810714, + VolumeUnit.AuTablespoon => _value * 2e-5, + VolumeUnit.BoardFoot => _value * 2.3597372158e-3, + VolumeUnit.Centiliter => (_value / 1e3) * 1e-2d, + VolumeUnit.CubicCentimeter => _value / 1e6, + VolumeUnit.CubicDecimeter => _value / 1e3, + VolumeUnit.CubicFoot => _value * 2.8316846592e-2, + VolumeUnit.CubicHectometer => _value * 1e6, + VolumeUnit.CubicInch => _value * 1.6387 * 1e-5, + VolumeUnit.CubicKilometer => _value * 1e9, + VolumeUnit.CubicMeter => _value, + VolumeUnit.CubicMicrometer => _value / 1e18, + VolumeUnit.CubicMile => _value * 4.16818182544058e9, + VolumeUnit.CubicMillimeter => _value / 1e9, + VolumeUnit.CubicYard => _value * 0.764554858, + VolumeUnit.Decaliter => (_value / 1e3) * 1e1d, + VolumeUnit.DecausGallon => (_value * 0.00378541) * 1e1d, + VolumeUnit.Deciliter => (_value / 1e3) * 1e-1d, + VolumeUnit.DeciusGallon => (_value * 0.00378541) * 1e-1d, + VolumeUnit.HectocubicFoot => (_value * 2.8316846592e-2) * 1e2d, + VolumeUnit.HectocubicMeter => (_value) * 1e2d, + VolumeUnit.Hectoliter => (_value / 1e3) * 1e2d, + VolumeUnit.HectousGallon => (_value * 0.00378541) * 1e2d, + VolumeUnit.ImperialBeerBarrel => _value * 0.16365924, + VolumeUnit.ImperialGallon => _value * 0.00454609000000181429905810072407, + VolumeUnit.ImperialOunce => _value * 2.8413062499962901241875439064617e-5, + VolumeUnit.ImperialPint => _value * 5.6826125e-4, + VolumeUnit.KilocubicFoot => (_value * 2.8316846592e-2) * 1e3d, + VolumeUnit.KilocubicMeter => (_value) * 1e3d, + VolumeUnit.KiloimperialGallon => (_value * 0.00454609000000181429905810072407) * 1e3d, + VolumeUnit.Kiloliter => (_value / 1e3) * 1e3d, + VolumeUnit.KilousGallon => (_value * 0.00378541) * 1e3d, + VolumeUnit.Liter => _value / 1e3, + VolumeUnit.MegacubicFoot => (_value * 2.8316846592e-2) * 1e6d, + VolumeUnit.MegaimperialGallon => (_value * 0.00454609000000181429905810072407) * 1e6d, + VolumeUnit.Megaliter => (_value / 1e3) * 1e6d, + VolumeUnit.MegausGallon => (_value * 0.00378541) * 1e6d, + VolumeUnit.MetricCup => _value * 0.00025, + VolumeUnit.MetricTeaspoon => _value * 0.5e-5, + VolumeUnit.Microliter => (_value / 1e3) * 1e-6d, + VolumeUnit.Milliliter => (_value / 1e3) * 1e-3d, + VolumeUnit.OilBarrel => _value * 0.158987294928, + VolumeUnit.UkTablespoon => _value * 1.5e-5, + VolumeUnit.UsBeerBarrel => _value * 0.1173477658, + VolumeUnit.UsCustomaryCup => _value * 0.0002365882365, + VolumeUnit.UsGallon => _value * 0.00378541, + VolumeUnit.UsLegalCup => _value * 0.00024, + VolumeUnit.UsOunce => _value * 2.957352956253760505068307980135e-5, + VolumeUnit.UsPint => _value * 4.73176473e-4, + VolumeUnit.UsQuart => _value * 9.46352946e-4, + VolumeUnit.UsTablespoon => _value * 1.478676478125e-5, + VolumeUnit.UsTeaspoon => _value * 4.92892159375e-6, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VolumeUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VolumeUnit.AcreFoot => baseUnitValue * 0.000810714, + VolumeUnit.AuTablespoon => baseUnitValue / 2e-5, + VolumeUnit.BoardFoot => baseUnitValue / 2.3597372158e-3, + VolumeUnit.Centiliter => (baseUnitValue * 1e3) / 1e-2d, + VolumeUnit.CubicCentimeter => baseUnitValue * 1e6, + VolumeUnit.CubicDecimeter => baseUnitValue * 1e3, + VolumeUnit.CubicFoot => baseUnitValue / 2.8316846592e-2, + VolumeUnit.CubicHectometer => baseUnitValue / 1e6, + VolumeUnit.CubicInch => baseUnitValue / (1.6387 * 1e-5), + VolumeUnit.CubicKilometer => baseUnitValue / 1e9, + VolumeUnit.CubicMeter => baseUnitValue, + VolumeUnit.CubicMicrometer => baseUnitValue * 1e18, + VolumeUnit.CubicMile => baseUnitValue / 4.16818182544058e9, + VolumeUnit.CubicMillimeter => baseUnitValue * 1e9, + VolumeUnit.CubicYard => baseUnitValue / 0.764554858, + VolumeUnit.Decaliter => (baseUnitValue * 1e3) / 1e1d, + VolumeUnit.DecausGallon => (baseUnitValue / 0.00378541) / 1e1d, + VolumeUnit.Deciliter => (baseUnitValue * 1e3) / 1e-1d, + VolumeUnit.DeciusGallon => (baseUnitValue / 0.00378541) / 1e-1d, + VolumeUnit.HectocubicFoot => (baseUnitValue / 2.8316846592e-2) / 1e2d, + VolumeUnit.HectocubicMeter => (baseUnitValue) / 1e2d, + VolumeUnit.Hectoliter => (baseUnitValue * 1e3) / 1e2d, + VolumeUnit.HectousGallon => (baseUnitValue / 0.00378541) / 1e2d, + VolumeUnit.ImperialBeerBarrel => baseUnitValue / 0.16365924, + VolumeUnit.ImperialGallon => baseUnitValue / 0.00454609000000181429905810072407, + VolumeUnit.ImperialOunce => baseUnitValue / 2.8413062499962901241875439064617e-5, + VolumeUnit.ImperialPint => baseUnitValue / 5.6826125e-4, + VolumeUnit.KilocubicFoot => (baseUnitValue / 2.8316846592e-2) / 1e3d, + VolumeUnit.KilocubicMeter => (baseUnitValue) / 1e3d, + VolumeUnit.KiloimperialGallon => (baseUnitValue / 0.00454609000000181429905810072407) / 1e3d, + VolumeUnit.Kiloliter => (baseUnitValue * 1e3) / 1e3d, + VolumeUnit.KilousGallon => (baseUnitValue / 0.00378541) / 1e3d, + VolumeUnit.Liter => baseUnitValue * 1e3, + VolumeUnit.MegacubicFoot => (baseUnitValue / 2.8316846592e-2) / 1e6d, + VolumeUnit.MegaimperialGallon => (baseUnitValue / 0.00454609000000181429905810072407) / 1e6d, + VolumeUnit.Megaliter => (baseUnitValue * 1e3) / 1e6d, + VolumeUnit.MegausGallon => (baseUnitValue / 0.00378541) / 1e6d, + VolumeUnit.MetricCup => baseUnitValue / 0.00025, + VolumeUnit.MetricTeaspoon => baseUnitValue / 0.5e-5, + VolumeUnit.Microliter => (baseUnitValue * 1e3) / 1e-6d, + VolumeUnit.Milliliter => (baseUnitValue * 1e3) / 1e-3d, + VolumeUnit.OilBarrel => baseUnitValue / 0.158987294928, + VolumeUnit.UkTablespoon => baseUnitValue / 1.5e-5, + VolumeUnit.UsBeerBarrel => baseUnitValue / 0.1173477658, + VolumeUnit.UsCustomaryCup => baseUnitValue / 0.0002365882365, + VolumeUnit.UsGallon => baseUnitValue / 0.00378541, + VolumeUnit.UsLegalCup => baseUnitValue / 0.00024, + VolumeUnit.UsOunce => baseUnitValue / 2.957352956253760505068307980135e-5, + VolumeUnit.UsPint => baseUnitValue / 4.73176473e-4, + VolumeUnit.UsQuart => baseUnitValue / 9.46352946e-4, + VolumeUnit.UsTablespoon => baseUnitValue / 1.478676478125e-5, + VolumeUnit.UsTeaspoon => baseUnitValue / 4.92892159375e-6, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeConcentration.g.cs index 3fdbfb0e01..2d69962960 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -319,91 +319,91 @@ public static VolumeConcentration From(double value, VolumeConcentrationUnit fro #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeConcentrationUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public VolumeConcentration ToUnit(VolumeConcentrationUnit unit) - { - var convertedValue = GetValueAs(unit); - return new VolumeConcentration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VolumeConcentrationUnit.CentilitersPerLiter => (_value) * 1e-2d, - VolumeConcentrationUnit.CentilitersPerMililiter => (_value / 1e-3) * 1e-2d, - VolumeConcentrationUnit.DecilitersPerLiter => (_value) * 1e-1d, - VolumeConcentrationUnit.DecilitersPerMililiter => (_value / 1e-3) * 1e-1d, - VolumeConcentrationUnit.DecimalFraction => _value, - VolumeConcentrationUnit.LitersPerLiter => _value, - VolumeConcentrationUnit.LitersPerMililiter => _value / 1e-3, - VolumeConcentrationUnit.MicrolitersPerLiter => (_value) * 1e-6d, - VolumeConcentrationUnit.MicrolitersPerMililiter => (_value / 1e-3) * 1e-6d, - VolumeConcentrationUnit.MillilitersPerLiter => (_value) * 1e-3d, - VolumeConcentrationUnit.MillilitersPerMililiter => (_value / 1e-3) * 1e-3d, - VolumeConcentrationUnit.NanolitersPerLiter => (_value) * 1e-9d, - VolumeConcentrationUnit.NanolitersPerMililiter => (_value / 1e-3) * 1e-9d, - VolumeConcentrationUnit.PartPerBillion => _value / 1e9, - VolumeConcentrationUnit.PartPerMillion => _value / 1e6, - VolumeConcentrationUnit.PartPerThousand => _value / 1e3, - VolumeConcentrationUnit.PartPerTrillion => _value / 1e12, - VolumeConcentrationUnit.Percent => _value / 1e2, - VolumeConcentrationUnit.PicolitersPerLiter => (_value) * 1e-12d, - VolumeConcentrationUnit.PicolitersPerMililiter => (_value / 1e-3) * 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VolumeConcentrationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VolumeConcentrationUnit.CentilitersPerLiter => (baseUnitValue) / 1e-2d, - VolumeConcentrationUnit.CentilitersPerMililiter => (baseUnitValue * 1e-3) / 1e-2d, - VolumeConcentrationUnit.DecilitersPerLiter => (baseUnitValue) / 1e-1d, - VolumeConcentrationUnit.DecilitersPerMililiter => (baseUnitValue * 1e-3) / 1e-1d, - VolumeConcentrationUnit.DecimalFraction => baseUnitValue, - VolumeConcentrationUnit.LitersPerLiter => baseUnitValue, - VolumeConcentrationUnit.LitersPerMililiter => baseUnitValue * 1e-3, - VolumeConcentrationUnit.MicrolitersPerLiter => (baseUnitValue) / 1e-6d, - VolumeConcentrationUnit.MicrolitersPerMililiter => (baseUnitValue * 1e-3) / 1e-6d, - VolumeConcentrationUnit.MillilitersPerLiter => (baseUnitValue) / 1e-3d, - VolumeConcentrationUnit.MillilitersPerMililiter => (baseUnitValue * 1e-3) / 1e-3d, - VolumeConcentrationUnit.NanolitersPerLiter => (baseUnitValue) / 1e-9d, - VolumeConcentrationUnit.NanolitersPerMililiter => (baseUnitValue * 1e-3) / 1e-9d, - VolumeConcentrationUnit.PartPerBillion => baseUnitValue * 1e9, - VolumeConcentrationUnit.PartPerMillion => baseUnitValue * 1e6, - VolumeConcentrationUnit.PartPerThousand => baseUnitValue * 1e3, - VolumeConcentrationUnit.PartPerTrillion => baseUnitValue * 1e12, - VolumeConcentrationUnit.Percent => baseUnitValue * 1e2, - VolumeConcentrationUnit.PicolitersPerLiter => (baseUnitValue) / 1e-12d, - VolumeConcentrationUnit.PicolitersPerMililiter => (baseUnitValue * 1e-3) / 1e-12d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeConcentrationUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public VolumeConcentration ToUnit(VolumeConcentrationUnit unit) + { + var convertedValue = GetValueAs(unit); + return new VolumeConcentration(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VolumeConcentrationUnit.CentilitersPerLiter => (_value) * 1e-2d, + VolumeConcentrationUnit.CentilitersPerMililiter => (_value / 1e-3) * 1e-2d, + VolumeConcentrationUnit.DecilitersPerLiter => (_value) * 1e-1d, + VolumeConcentrationUnit.DecilitersPerMililiter => (_value / 1e-3) * 1e-1d, + VolumeConcentrationUnit.DecimalFraction => _value, + VolumeConcentrationUnit.LitersPerLiter => _value, + VolumeConcentrationUnit.LitersPerMililiter => _value / 1e-3, + VolumeConcentrationUnit.MicrolitersPerLiter => (_value) * 1e-6d, + VolumeConcentrationUnit.MicrolitersPerMililiter => (_value / 1e-3) * 1e-6d, + VolumeConcentrationUnit.MillilitersPerLiter => (_value) * 1e-3d, + VolumeConcentrationUnit.MillilitersPerMililiter => (_value / 1e-3) * 1e-3d, + VolumeConcentrationUnit.NanolitersPerLiter => (_value) * 1e-9d, + VolumeConcentrationUnit.NanolitersPerMililiter => (_value / 1e-3) * 1e-9d, + VolumeConcentrationUnit.PartPerBillion => _value / 1e9, + VolumeConcentrationUnit.PartPerMillion => _value / 1e6, + VolumeConcentrationUnit.PartPerThousand => _value / 1e3, + VolumeConcentrationUnit.PartPerTrillion => _value / 1e12, + VolumeConcentrationUnit.Percent => _value / 1e2, + VolumeConcentrationUnit.PicolitersPerLiter => (_value) * 1e-12d, + VolumeConcentrationUnit.PicolitersPerMililiter => (_value / 1e-3) * 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VolumeConcentrationUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VolumeConcentrationUnit.CentilitersPerLiter => (baseUnitValue) / 1e-2d, + VolumeConcentrationUnit.CentilitersPerMililiter => (baseUnitValue * 1e-3) / 1e-2d, + VolumeConcentrationUnit.DecilitersPerLiter => (baseUnitValue) / 1e-1d, + VolumeConcentrationUnit.DecilitersPerMililiter => (baseUnitValue * 1e-3) / 1e-1d, + VolumeConcentrationUnit.DecimalFraction => baseUnitValue, + VolumeConcentrationUnit.LitersPerLiter => baseUnitValue, + VolumeConcentrationUnit.LitersPerMililiter => baseUnitValue * 1e-3, + VolumeConcentrationUnit.MicrolitersPerLiter => (baseUnitValue) / 1e-6d, + VolumeConcentrationUnit.MicrolitersPerMililiter => (baseUnitValue * 1e-3) / 1e-6d, + VolumeConcentrationUnit.MillilitersPerLiter => (baseUnitValue) / 1e-3d, + VolumeConcentrationUnit.MillilitersPerMililiter => (baseUnitValue * 1e-3) / 1e-3d, + VolumeConcentrationUnit.NanolitersPerLiter => (baseUnitValue) / 1e-9d, + VolumeConcentrationUnit.NanolitersPerMililiter => (baseUnitValue * 1e-3) / 1e-9d, + VolumeConcentrationUnit.PartPerBillion => baseUnitValue * 1e9, + VolumeConcentrationUnit.PartPerMillion => baseUnitValue * 1e6, + VolumeConcentrationUnit.PartPerThousand => baseUnitValue * 1e3, + VolumeConcentrationUnit.PartPerTrillion => baseUnitValue * 1e12, + VolumeConcentrationUnit.Percent => baseUnitValue * 1e2, + VolumeConcentrationUnit.PicolitersPerLiter => (baseUnitValue) / 1e-12d, + VolumeConcentrationUnit.PicolitersPerMililiter => (baseUnitValue * 1e-3) / 1e-12d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlow.g.cs index baf6e13ada..13a0d49c43 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -305,9 +305,9 @@ public VolumeFlow(double value, VolumeFlowUnit unit) public double MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); + public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonPerDay); /// /// Gets a value of this quantity converted into @@ -664,10 +664,10 @@ public VolumeFlow(double value, VolumeFlowUnit unit) public static VolumeFlow FromMillilitersPerSecond(double milliliterspersecond) => new VolumeFlow(milliliterspersecond, VolumeFlowUnit.MilliliterPerSecond); /// - /// Creates a from . + /// Creates a from . /// /// If value is NaN or Infinity. - public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) => new VolumeFlow(millionusgallonsperday, VolumeFlowUnit.MillionUsGallonsPerDay); + public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) => new VolumeFlow(millionusgallonsperday, VolumeFlowUnit.MillionUsGallonPerDay); /// /// Creates a from . @@ -778,175 +778,175 @@ public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public VolumeFlow ToUnit(VolumeFlowUnit unit) - { - var convertedValue = GetValueAs(unit); - return new VolumeFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VolumeFlowUnit.AcreFootPerDay => _value / 70.0457, - VolumeFlowUnit.AcreFootPerHour => _value / 2.91857, - VolumeFlowUnit.AcreFootPerMinute => _value / 0.0486427916, - VolumeFlowUnit.AcreFootPerSecond => _value / 0.000810713194, - VolumeFlowUnit.CentiliterPerDay => (_value / 86400000) * 1e-2d, - VolumeFlowUnit.CentiliterPerHour => (_value / 3600000.000) * 1e-2d, - VolumeFlowUnit.CentiliterPerMinute => (_value / 60000.00000) * 1e-2d, - VolumeFlowUnit.CentiliterPerSecond => (_value / 1000) * 1e-2d, - VolumeFlowUnit.CubicCentimeterPerMinute => _value * 1.6666666666667e-8, - VolumeFlowUnit.CubicDecimeterPerMinute => _value / 60000.00000, - VolumeFlowUnit.CubicFootPerHour => _value * 7.8657907199999087346816086183876e-6, - VolumeFlowUnit.CubicFootPerMinute => _value / 2118.88000326, - VolumeFlowUnit.CubicFootPerSecond => _value / 35.314666721, - VolumeFlowUnit.CubicMeterPerDay => _value / 86400, - VolumeFlowUnit.CubicMeterPerHour => _value / 3600, - VolumeFlowUnit.CubicMeterPerMinute => _value / 60, - VolumeFlowUnit.CubicMeterPerSecond => _value, - VolumeFlowUnit.CubicMillimeterPerSecond => _value * 1e-9, - VolumeFlowUnit.CubicYardPerDay => _value / 113007, - VolumeFlowUnit.CubicYardPerHour => _value * 2.1237634944E-4, - VolumeFlowUnit.CubicYardPerMinute => _value * 0.0127425809664, - VolumeFlowUnit.CubicYardPerSecond => _value * 0.764554857984, - VolumeFlowUnit.DeciliterPerDay => (_value / 86400000) * 1e-1d, - VolumeFlowUnit.DeciliterPerHour => (_value / 3600000.000) * 1e-1d, - VolumeFlowUnit.DeciliterPerMinute => (_value / 60000.00000) * 1e-1d, - VolumeFlowUnit.DeciliterPerSecond => (_value / 1000) * 1e-1d, - VolumeFlowUnit.KiloliterPerDay => (_value / 86400000) * 1e3d, - VolumeFlowUnit.KiloliterPerHour => (_value / 3600000.000) * 1e3d, - VolumeFlowUnit.KiloliterPerMinute => (_value / 60000.00000) * 1e3d, - VolumeFlowUnit.KiloliterPerSecond => (_value / 1000) * 1e3d, - VolumeFlowUnit.KilousGallonPerMinute => _value / 15.850323141489, - VolumeFlowUnit.LiterPerDay => _value / 86400000, - VolumeFlowUnit.LiterPerHour => _value / 3600000.000, - VolumeFlowUnit.LiterPerMinute => _value / 60000.00000, - VolumeFlowUnit.LiterPerSecond => _value / 1000, - VolumeFlowUnit.MegaliterPerDay => (_value / 86400000) * 1e6d, - VolumeFlowUnit.MegaukGallonPerSecond => (_value / 219.969) * 1e6d, - VolumeFlowUnit.MicroliterPerDay => (_value / 86400000) * 1e-6d, - VolumeFlowUnit.MicroliterPerHour => (_value / 3600000.000) * 1e-6d, - VolumeFlowUnit.MicroliterPerMinute => (_value / 60000.00000) * 1e-6d, - VolumeFlowUnit.MicroliterPerSecond => (_value / 1000) * 1e-6d, - VolumeFlowUnit.MilliliterPerDay => (_value / 86400000) * 1e-3d, - VolumeFlowUnit.MilliliterPerHour => (_value / 3600000.000) * 1e-3d, - VolumeFlowUnit.MilliliterPerMinute => (_value / 60000.00000) * 1e-3d, - VolumeFlowUnit.MilliliterPerSecond => (_value / 1000) * 1e-3d, - VolumeFlowUnit.MillionUsGallonsPerDay => _value / 22.824465227, - VolumeFlowUnit.NanoliterPerDay => (_value / 86400000) * 1e-9d, - VolumeFlowUnit.NanoliterPerHour => (_value / 3600000.000) * 1e-9d, - VolumeFlowUnit.NanoliterPerMinute => (_value / 60000.00000) * 1e-9d, - VolumeFlowUnit.NanoliterPerSecond => (_value / 1000) * 1e-9d, - VolumeFlowUnit.OilBarrelPerDay => _value * 1.8401307283333333333333333333333e-6, - VolumeFlowUnit.OilBarrelPerHour => _value * 4.41631375e-5, - VolumeFlowUnit.OilBarrelPerMinute => _value * 2.64978825e-3, - VolumeFlowUnit.OilBarrelPerSecond => _value / 6.28981, - VolumeFlowUnit.UkGallonPerDay => _value / 19005304, - VolumeFlowUnit.UkGallonPerHour => _value / 791887.667, - VolumeFlowUnit.UkGallonPerMinute => _value / 13198.2, - VolumeFlowUnit.UkGallonPerSecond => _value / 219.969, - VolumeFlowUnit.UsGallonPerDay => _value / 22824465.227, - VolumeFlowUnit.UsGallonPerHour => _value / 951019.38848933424, - VolumeFlowUnit.UsGallonPerMinute => _value / 15850.323141489, - VolumeFlowUnit.UsGallonPerSecond => _value / 264.1720523581484, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VolumeFlowUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VolumeFlowUnit.AcreFootPerDay => baseUnitValue * 70.0457, - VolumeFlowUnit.AcreFootPerHour => baseUnitValue * 2.91857, - VolumeFlowUnit.AcreFootPerMinute => baseUnitValue * 0.0486427916, - VolumeFlowUnit.AcreFootPerSecond => baseUnitValue * 0.000810713194, - VolumeFlowUnit.CentiliterPerDay => (baseUnitValue * 86400000) / 1e-2d, - VolumeFlowUnit.CentiliterPerHour => (baseUnitValue * 3600000.000) / 1e-2d, - VolumeFlowUnit.CentiliterPerMinute => (baseUnitValue * 60000.00000) / 1e-2d, - VolumeFlowUnit.CentiliterPerSecond => (baseUnitValue * 1000) / 1e-2d, - VolumeFlowUnit.CubicCentimeterPerMinute => baseUnitValue / 1.6666666666667e-8, - VolumeFlowUnit.CubicDecimeterPerMinute => baseUnitValue * 60000.00000, - VolumeFlowUnit.CubicFootPerHour => baseUnitValue / 7.8657907199999087346816086183876e-6, - VolumeFlowUnit.CubicFootPerMinute => baseUnitValue * 2118.88000326, - VolumeFlowUnit.CubicFootPerSecond => baseUnitValue * 35.314666721, - VolumeFlowUnit.CubicMeterPerDay => baseUnitValue * 86400, - VolumeFlowUnit.CubicMeterPerHour => baseUnitValue * 3600, - VolumeFlowUnit.CubicMeterPerMinute => baseUnitValue * 60, - VolumeFlowUnit.CubicMeterPerSecond => baseUnitValue, - VolumeFlowUnit.CubicMillimeterPerSecond => baseUnitValue / 1e-9, - VolumeFlowUnit.CubicYardPerDay => baseUnitValue * 113007, - VolumeFlowUnit.CubicYardPerHour => baseUnitValue / 2.1237634944E-4, - VolumeFlowUnit.CubicYardPerMinute => baseUnitValue / 0.0127425809664, - VolumeFlowUnit.CubicYardPerSecond => baseUnitValue / 0.764554857984, - VolumeFlowUnit.DeciliterPerDay => (baseUnitValue * 86400000) / 1e-1d, - VolumeFlowUnit.DeciliterPerHour => (baseUnitValue * 3600000.000) / 1e-1d, - VolumeFlowUnit.DeciliterPerMinute => (baseUnitValue * 60000.00000) / 1e-1d, - VolumeFlowUnit.DeciliterPerSecond => (baseUnitValue * 1000) / 1e-1d, - VolumeFlowUnit.KiloliterPerDay => (baseUnitValue * 86400000) / 1e3d, - VolumeFlowUnit.KiloliterPerHour => (baseUnitValue * 3600000.000) / 1e3d, - VolumeFlowUnit.KiloliterPerMinute => (baseUnitValue * 60000.00000) / 1e3d, - VolumeFlowUnit.KiloliterPerSecond => (baseUnitValue * 1000) / 1e3d, - VolumeFlowUnit.KilousGallonPerMinute => baseUnitValue * 15.850323141489, - VolumeFlowUnit.LiterPerDay => baseUnitValue * 86400000, - VolumeFlowUnit.LiterPerHour => baseUnitValue * 3600000.000, - VolumeFlowUnit.LiterPerMinute => baseUnitValue * 60000.00000, - VolumeFlowUnit.LiterPerSecond => baseUnitValue * 1000, - VolumeFlowUnit.MegaliterPerDay => (baseUnitValue * 86400000) / 1e6d, - VolumeFlowUnit.MegaukGallonPerSecond => (baseUnitValue * 219.969) / 1e6d, - VolumeFlowUnit.MicroliterPerDay => (baseUnitValue * 86400000) / 1e-6d, - VolumeFlowUnit.MicroliterPerHour => (baseUnitValue * 3600000.000) / 1e-6d, - VolumeFlowUnit.MicroliterPerMinute => (baseUnitValue * 60000.00000) / 1e-6d, - VolumeFlowUnit.MicroliterPerSecond => (baseUnitValue * 1000) / 1e-6d, - VolumeFlowUnit.MilliliterPerDay => (baseUnitValue * 86400000) / 1e-3d, - VolumeFlowUnit.MilliliterPerHour => (baseUnitValue * 3600000.000) / 1e-3d, - VolumeFlowUnit.MilliliterPerMinute => (baseUnitValue * 60000.00000) / 1e-3d, - VolumeFlowUnit.MilliliterPerSecond => (baseUnitValue * 1000) / 1e-3d, - VolumeFlowUnit.MillionUsGallonsPerDay => baseUnitValue * 22.824465227, - VolumeFlowUnit.NanoliterPerDay => (baseUnitValue * 86400000) / 1e-9d, - VolumeFlowUnit.NanoliterPerHour => (baseUnitValue * 3600000.000) / 1e-9d, - VolumeFlowUnit.NanoliterPerMinute => (baseUnitValue * 60000.00000) / 1e-9d, - VolumeFlowUnit.NanoliterPerSecond => (baseUnitValue * 1000) / 1e-9d, - VolumeFlowUnit.OilBarrelPerDay => baseUnitValue / 1.8401307283333333333333333333333e-6, - VolumeFlowUnit.OilBarrelPerHour => baseUnitValue / 4.41631375e-5, - VolumeFlowUnit.OilBarrelPerMinute => baseUnitValue / 2.64978825e-3, - VolumeFlowUnit.OilBarrelPerSecond => baseUnitValue * 6.28981, - VolumeFlowUnit.UkGallonPerDay => baseUnitValue * 19005304, - VolumeFlowUnit.UkGallonPerHour => baseUnitValue * 791887.667, - VolumeFlowUnit.UkGallonPerMinute => baseUnitValue * 13198.2, - VolumeFlowUnit.UkGallonPerSecond => baseUnitValue * 219.969, - VolumeFlowUnit.UsGallonPerDay => baseUnitValue * 22824465.227, - VolumeFlowUnit.UsGallonPerHour => baseUnitValue * 951019.38848933424, - VolumeFlowUnit.UsGallonPerMinute => baseUnitValue * 15850.323141489, - VolumeFlowUnit.UsGallonPerSecond => baseUnitValue * 264.1720523581484, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeFlowUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public VolumeFlow ToUnit(VolumeFlowUnit unit) + { + var convertedValue = GetValueAs(unit); + return new VolumeFlow(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VolumeFlowUnit.AcreFootPerDay => _value / 70.0457, + VolumeFlowUnit.AcreFootPerHour => _value / 2.91857, + VolumeFlowUnit.AcreFootPerMinute => _value / 0.0486427916, + VolumeFlowUnit.AcreFootPerSecond => _value / 0.000810713194, + VolumeFlowUnit.CentiliterPerDay => (_value / 86400000) * 1e-2d, + VolumeFlowUnit.CentiliterPerHour => (_value / 3600000.000) * 1e-2d, + VolumeFlowUnit.CentiliterPerMinute => (_value / 60000.00000) * 1e-2d, + VolumeFlowUnit.CentiliterPerSecond => (_value / 1000) * 1e-2d, + VolumeFlowUnit.CubicCentimeterPerMinute => _value * 1.6666666666667e-8, + VolumeFlowUnit.CubicDecimeterPerMinute => _value / 60000.00000, + VolumeFlowUnit.CubicFootPerHour => _value * 7.8657907199999087346816086183876e-6, + VolumeFlowUnit.CubicFootPerMinute => _value / 2118.88000326, + VolumeFlowUnit.CubicFootPerSecond => _value / 35.314666721, + VolumeFlowUnit.CubicMeterPerDay => _value / 86400, + VolumeFlowUnit.CubicMeterPerHour => _value / 3600, + VolumeFlowUnit.CubicMeterPerMinute => _value / 60, + VolumeFlowUnit.CubicMeterPerSecond => _value, + VolumeFlowUnit.CubicMillimeterPerSecond => _value * 1e-9, + VolumeFlowUnit.CubicYardPerDay => _value / 113007, + VolumeFlowUnit.CubicYardPerHour => _value * 2.1237634944E-4, + VolumeFlowUnit.CubicYardPerMinute => _value * 0.0127425809664, + VolumeFlowUnit.CubicYardPerSecond => _value * 0.764554857984, + VolumeFlowUnit.DeciliterPerDay => (_value / 86400000) * 1e-1d, + VolumeFlowUnit.DeciliterPerHour => (_value / 3600000.000) * 1e-1d, + VolumeFlowUnit.DeciliterPerMinute => (_value / 60000.00000) * 1e-1d, + VolumeFlowUnit.DeciliterPerSecond => (_value / 1000) * 1e-1d, + VolumeFlowUnit.KiloliterPerDay => (_value / 86400000) * 1e3d, + VolumeFlowUnit.KiloliterPerHour => (_value / 3600000.000) * 1e3d, + VolumeFlowUnit.KiloliterPerMinute => (_value / 60000.00000) * 1e3d, + VolumeFlowUnit.KiloliterPerSecond => (_value / 1000) * 1e3d, + VolumeFlowUnit.KilousGallonPerMinute => _value / 15.850323141489, + VolumeFlowUnit.LiterPerDay => _value / 86400000, + VolumeFlowUnit.LiterPerHour => _value / 3600000.000, + VolumeFlowUnit.LiterPerMinute => _value / 60000.00000, + VolumeFlowUnit.LiterPerSecond => _value / 1000, + VolumeFlowUnit.MegaliterPerDay => (_value / 86400000) * 1e6d, + VolumeFlowUnit.MegaukGallonPerSecond => (_value / 219.969) * 1e6d, + VolumeFlowUnit.MicroliterPerDay => (_value / 86400000) * 1e-6d, + VolumeFlowUnit.MicroliterPerHour => (_value / 3600000.000) * 1e-6d, + VolumeFlowUnit.MicroliterPerMinute => (_value / 60000.00000) * 1e-6d, + VolumeFlowUnit.MicroliterPerSecond => (_value / 1000) * 1e-6d, + VolumeFlowUnit.MilliliterPerDay => (_value / 86400000) * 1e-3d, + VolumeFlowUnit.MilliliterPerHour => (_value / 3600000.000) * 1e-3d, + VolumeFlowUnit.MilliliterPerMinute => (_value / 60000.00000) * 1e-3d, + VolumeFlowUnit.MilliliterPerSecond => (_value / 1000) * 1e-3d, + VolumeFlowUnit.MillionUsGallonPerDay => _value / 22.824465227, + VolumeFlowUnit.NanoliterPerDay => (_value / 86400000) * 1e-9d, + VolumeFlowUnit.NanoliterPerHour => (_value / 3600000.000) * 1e-9d, + VolumeFlowUnit.NanoliterPerMinute => (_value / 60000.00000) * 1e-9d, + VolumeFlowUnit.NanoliterPerSecond => (_value / 1000) * 1e-9d, + VolumeFlowUnit.OilBarrelPerDay => _value * 1.8401307283333333333333333333333e-6, + VolumeFlowUnit.OilBarrelPerHour => _value * 4.41631375e-5, + VolumeFlowUnit.OilBarrelPerMinute => _value * 2.64978825e-3, + VolumeFlowUnit.OilBarrelPerSecond => _value / 6.28981, + VolumeFlowUnit.UkGallonPerDay => _value / 19005304, + VolumeFlowUnit.UkGallonPerHour => _value / 791887.667, + VolumeFlowUnit.UkGallonPerMinute => _value / 13198.2, + VolumeFlowUnit.UkGallonPerSecond => _value / 219.969, + VolumeFlowUnit.UsGallonPerDay => _value / 22824465.227, + VolumeFlowUnit.UsGallonPerHour => _value / 951019.38848933424, + VolumeFlowUnit.UsGallonPerMinute => _value / 15850.323141489, + VolumeFlowUnit.UsGallonPerSecond => _value / 264.1720523581484, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VolumeFlowUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VolumeFlowUnit.AcreFootPerDay => baseUnitValue * 70.0457, + VolumeFlowUnit.AcreFootPerHour => baseUnitValue * 2.91857, + VolumeFlowUnit.AcreFootPerMinute => baseUnitValue * 0.0486427916, + VolumeFlowUnit.AcreFootPerSecond => baseUnitValue * 0.000810713194, + VolumeFlowUnit.CentiliterPerDay => (baseUnitValue * 86400000) / 1e-2d, + VolumeFlowUnit.CentiliterPerHour => (baseUnitValue * 3600000.000) / 1e-2d, + VolumeFlowUnit.CentiliterPerMinute => (baseUnitValue * 60000.00000) / 1e-2d, + VolumeFlowUnit.CentiliterPerSecond => (baseUnitValue * 1000) / 1e-2d, + VolumeFlowUnit.CubicCentimeterPerMinute => baseUnitValue / 1.6666666666667e-8, + VolumeFlowUnit.CubicDecimeterPerMinute => baseUnitValue * 60000.00000, + VolumeFlowUnit.CubicFootPerHour => baseUnitValue / 7.8657907199999087346816086183876e-6, + VolumeFlowUnit.CubicFootPerMinute => baseUnitValue * 2118.88000326, + VolumeFlowUnit.CubicFootPerSecond => baseUnitValue * 35.314666721, + VolumeFlowUnit.CubicMeterPerDay => baseUnitValue * 86400, + VolumeFlowUnit.CubicMeterPerHour => baseUnitValue * 3600, + VolumeFlowUnit.CubicMeterPerMinute => baseUnitValue * 60, + VolumeFlowUnit.CubicMeterPerSecond => baseUnitValue, + VolumeFlowUnit.CubicMillimeterPerSecond => baseUnitValue / 1e-9, + VolumeFlowUnit.CubicYardPerDay => baseUnitValue * 113007, + VolumeFlowUnit.CubicYardPerHour => baseUnitValue / 2.1237634944E-4, + VolumeFlowUnit.CubicYardPerMinute => baseUnitValue / 0.0127425809664, + VolumeFlowUnit.CubicYardPerSecond => baseUnitValue / 0.764554857984, + VolumeFlowUnit.DeciliterPerDay => (baseUnitValue * 86400000) / 1e-1d, + VolumeFlowUnit.DeciliterPerHour => (baseUnitValue * 3600000.000) / 1e-1d, + VolumeFlowUnit.DeciliterPerMinute => (baseUnitValue * 60000.00000) / 1e-1d, + VolumeFlowUnit.DeciliterPerSecond => (baseUnitValue * 1000) / 1e-1d, + VolumeFlowUnit.KiloliterPerDay => (baseUnitValue * 86400000) / 1e3d, + VolumeFlowUnit.KiloliterPerHour => (baseUnitValue * 3600000.000) / 1e3d, + VolumeFlowUnit.KiloliterPerMinute => (baseUnitValue * 60000.00000) / 1e3d, + VolumeFlowUnit.KiloliterPerSecond => (baseUnitValue * 1000) / 1e3d, + VolumeFlowUnit.KilousGallonPerMinute => baseUnitValue * 15.850323141489, + VolumeFlowUnit.LiterPerDay => baseUnitValue * 86400000, + VolumeFlowUnit.LiterPerHour => baseUnitValue * 3600000.000, + VolumeFlowUnit.LiterPerMinute => baseUnitValue * 60000.00000, + VolumeFlowUnit.LiterPerSecond => baseUnitValue * 1000, + VolumeFlowUnit.MegaliterPerDay => (baseUnitValue * 86400000) / 1e6d, + VolumeFlowUnit.MegaukGallonPerSecond => (baseUnitValue * 219.969) / 1e6d, + VolumeFlowUnit.MicroliterPerDay => (baseUnitValue * 86400000) / 1e-6d, + VolumeFlowUnit.MicroliterPerHour => (baseUnitValue * 3600000.000) / 1e-6d, + VolumeFlowUnit.MicroliterPerMinute => (baseUnitValue * 60000.00000) / 1e-6d, + VolumeFlowUnit.MicroliterPerSecond => (baseUnitValue * 1000) / 1e-6d, + VolumeFlowUnit.MilliliterPerDay => (baseUnitValue * 86400000) / 1e-3d, + VolumeFlowUnit.MilliliterPerHour => (baseUnitValue * 3600000.000) / 1e-3d, + VolumeFlowUnit.MilliliterPerMinute => (baseUnitValue * 60000.00000) / 1e-3d, + VolumeFlowUnit.MilliliterPerSecond => (baseUnitValue * 1000) / 1e-3d, + VolumeFlowUnit.MillionUsGallonPerDay => baseUnitValue * 22.824465227, + VolumeFlowUnit.NanoliterPerDay => (baseUnitValue * 86400000) / 1e-9d, + VolumeFlowUnit.NanoliterPerHour => (baseUnitValue * 3600000.000) / 1e-9d, + VolumeFlowUnit.NanoliterPerMinute => (baseUnitValue * 60000.00000) / 1e-9d, + VolumeFlowUnit.NanoliterPerSecond => (baseUnitValue * 1000) / 1e-9d, + VolumeFlowUnit.OilBarrelPerDay => baseUnitValue / 1.8401307283333333333333333333333e-6, + VolumeFlowUnit.OilBarrelPerHour => baseUnitValue / 4.41631375e-5, + VolumeFlowUnit.OilBarrelPerMinute => baseUnitValue / 2.64978825e-3, + VolumeFlowUnit.OilBarrelPerSecond => baseUnitValue * 6.28981, + VolumeFlowUnit.UkGallonPerDay => baseUnitValue * 19005304, + VolumeFlowUnit.UkGallonPerHour => baseUnitValue * 791887.667, + VolumeFlowUnit.UkGallonPerMinute => baseUnitValue * 13198.2, + VolumeFlowUnit.UkGallonPerSecond => baseUnitValue * 219.969, + VolumeFlowUnit.UsGallonPerDay => baseUnitValue * 22824465.227, + VolumeFlowUnit.UsGallonPerHour => baseUnitValue * 951019.38848933424, + VolumeFlowUnit.UsGallonPerMinute => baseUnitValue * 15850.323141489, + VolumeFlowUnit.UsGallonPerSecond => baseUnitValue * 264.1720523581484, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index 7e15ddca65..d35c8c82e0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -24,7 +24,7 @@ namespace UnitsNet { /// /// - /// The volumetric flow rate per area is the volume of fluid which passes through a given unit surface area per unit time. + /// /// public struct VolumeFlowPerArea { @@ -118,55 +118,55 @@ public static VolumeFlowPerArea From(double value, VolumeFlowPerAreaUnit fromUni #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowPerAreaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new VolumeFlowPerArea(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot => _value / 196.850394, - VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter => _value, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VolumeFlowPerAreaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot => baseUnitValue * 196.850394, - VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter => baseUnitValue, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumeFlowPerAreaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new VolumeFlowPerArea(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot => _value / 196.850394, + VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter => _value, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VolumeFlowPerAreaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot => baseUnitValue * 196.850394, + VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter => baseUnitValue, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumePerLength.g.cs index 24a664b556..4d202492b0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -173,65 +173,65 @@ public static VolumePerLength From(double value, VolumePerLengthUnit fromUnit) #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumePerLengthUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public VolumePerLength ToUnit(VolumePerLengthUnit unit) - { - var convertedValue = GetValueAs(unit); - return new VolumePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VolumePerLengthUnit.CubicMeterPerMeter => _value, - VolumePerLengthUnit.CubicYardPerFoot => _value * 2.50838208, - VolumePerLengthUnit.CubicYardPerUsSurveyFoot => _value * 2.50837706323584, - VolumePerLengthUnit.LiterPerKilometer => _value / 1e6, - VolumePerLengthUnit.LiterPerMeter => _value / 1000, - VolumePerLengthUnit.LiterPerMillimeter => _value, - VolumePerLengthUnit.OilBarrelPerFoot => _value / 1.91713408, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VolumePerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VolumePerLengthUnit.CubicMeterPerMeter => baseUnitValue, - VolumePerLengthUnit.CubicYardPerFoot => baseUnitValue / 2.50838208, - VolumePerLengthUnit.CubicYardPerUsSurveyFoot => baseUnitValue / 2.50837706323584, - VolumePerLengthUnit.LiterPerKilometer => baseUnitValue * 1e6, - VolumePerLengthUnit.LiterPerMeter => baseUnitValue * 1000, - VolumePerLengthUnit.LiterPerMillimeter => baseUnitValue, - VolumePerLengthUnit.OilBarrelPerFoot => baseUnitValue * 1.91713408, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumePerLengthUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public VolumePerLength ToUnit(VolumePerLengthUnit unit) + { + var convertedValue = GetValueAs(unit); + return new VolumePerLength(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VolumePerLengthUnit.CubicMeterPerMeter => _value, + VolumePerLengthUnit.CubicYardPerFoot => _value * 2.50838208, + VolumePerLengthUnit.CubicYardPerUsSurveyFoot => _value * 2.50837706323584, + VolumePerLengthUnit.LiterPerKilometer => _value / 1e6, + VolumePerLengthUnit.LiterPerMeter => _value / 1000, + VolumePerLengthUnit.LiterPerMillimeter => _value, + VolumePerLengthUnit.OilBarrelPerFoot => _value / 1.91713408, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VolumePerLengthUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VolumePerLengthUnit.CubicMeterPerMeter => baseUnitValue, + VolumePerLengthUnit.CubicYardPerFoot => baseUnitValue / 2.50838208, + VolumePerLengthUnit.CubicYardPerUsSurveyFoot => baseUnitValue / 2.50837706323584, + VolumePerLengthUnit.LiterPerKilometer => baseUnitValue * 1e6, + VolumePerLengthUnit.LiterPerMeter => baseUnitValue * 1000, + VolumePerLengthUnit.LiterPerMillimeter => baseUnitValue, + VolumePerLengthUnit.OilBarrelPerFoot => baseUnitValue * 1.91713408, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index 8b099e7fc7..d487356595 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -198,69 +198,69 @@ public static VolumetricHeatCapacity From(double value, VolumetricHeatCapacityUn #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumetricHeatCapacityUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit) - { - var convertedValue = GetValueAs(unit); - return new VolumetricHeatCapacity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit => _value / 1.4910660e-5, - VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius => _value / 2.388459e-7, - VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius => _value, - VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin => _value, - VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius => (_value / 2.388459e-7) * 1e3d, - VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius => (_value) * 1e3d, - VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin => (_value) * 1e3d, - VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius => (_value) * 1e6d, - VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin => (_value) * 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(VolumetricHeatCapacityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit => baseUnitValue * 1.4910660e-5, - VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius => baseUnitValue * 2.388459e-7, - VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius => baseUnitValue, - VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin => baseUnitValue, - VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius => (baseUnitValue * 2.388459e-7) / 1e3d, - VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius => (baseUnitValue) / 1e3d, - VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin => (baseUnitValue) / 1e3d, - VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius => (baseUnitValue) / 1e6d, - VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin => (baseUnitValue) / 1e6d, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(VolumetricHeatCapacityUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit) + { + var convertedValue = GetValueAs(unit); + return new VolumetricHeatCapacity(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit => _value / 1.4910660e-5, + VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius => _value / 2.388459e-7, + VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius => _value, + VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin => _value, + VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius => (_value / 2.388459e-7) * 1e3d, + VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius => (_value) * 1e3d, + VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin => (_value) * 1e3d, + VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius => (_value) * 1e6d, + VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin => (_value) * 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(VolumetricHeatCapacityUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit => baseUnitValue * 1.4910660e-5, + VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius => baseUnitValue * 2.388459e-7, + VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius => baseUnitValue, + VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin => baseUnitValue, + VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius => (baseUnitValue * 2.388459e-7) / 1e3d, + VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius => (baseUnitValue) / 1e3d, + VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin => (baseUnitValue) / 1e3d, + VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius => (baseUnitValue) / 1e6d, + VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin => (baseUnitValue) / 1e6d, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index 688f69a79b..f21bb0887e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -162,63 +162,63 @@ public static WarpingMomentOfInertia From(double value, WarpingMomentOfInertiaUn #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(WarpingMomentOfInertiaUnit unit) => GetValueAs(unit); - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit) - { - var convertedValue = GetValueAs(unit); - return new WarpingMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double GetValueInBaseUnit() - { - return Unit switch - { - WarpingMomentOfInertiaUnit.CentimeterToTheSixth => _value / 1e12, - WarpingMomentOfInertiaUnit.DecimeterToTheSixth => _value / 1e6, - WarpingMomentOfInertiaUnit.FootToTheSixth => _value * Math.Pow(0.3048, 6), - WarpingMomentOfInertiaUnit.InchToTheSixth => _value * Math.Pow(2.54e-2, 6), - WarpingMomentOfInertiaUnit.MeterToTheSixth => _value, - WarpingMomentOfInertiaUnit.MillimeterToTheSixth => _value / 1e18, - _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") - }; - } - - private double GetValueAs(WarpingMomentOfInertiaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = GetValueInBaseUnit(); - - return unit switch - { - WarpingMomentOfInertiaUnit.CentimeterToTheSixth => baseUnitValue * 1e12, - WarpingMomentOfInertiaUnit.DecimeterToTheSixth => baseUnitValue * 1e6, - WarpingMomentOfInertiaUnit.FootToTheSixth => baseUnitValue / Math.Pow(0.3048, 6), - WarpingMomentOfInertiaUnit.InchToTheSixth => baseUnitValue / Math.Pow(2.54e-2, 6), - WarpingMomentOfInertiaUnit.MeterToTheSixth => baseUnitValue, - WarpingMomentOfInertiaUnit.MillimeterToTheSixth => baseUnitValue * 1e18, - _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") - }; - } - - #endregion + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(WarpingMomentOfInertiaUnit unit) => GetValueAs(unit); + + /// + /// Converts this Duration to another Duration with the unit representation . + /// + /// A Duration with the specified unit. + public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit) + { + var convertedValue = GetValueAs(unit); + return new WarpingMomentOfInertia(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + WarpingMomentOfInertiaUnit.CentimeterToTheSixth => _value / 1e12, + WarpingMomentOfInertiaUnit.DecimeterToTheSixth => _value / 1e6, + WarpingMomentOfInertiaUnit.FootToTheSixth => _value * Math.Pow(0.3048, 6), + WarpingMomentOfInertiaUnit.InchToTheSixth => _value * Math.Pow(2.54e-2, 6), + WarpingMomentOfInertiaUnit.MeterToTheSixth => _value, + WarpingMomentOfInertiaUnit.MillimeterToTheSixth => _value / 1e18, + _ => throw new NotImplementedException($"Can not convert {Unit} to base units.") + }; + } + + private double GetValueAs(WarpingMomentOfInertiaUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + WarpingMomentOfInertiaUnit.CentimeterToTheSixth => baseUnitValue * 1e12, + WarpingMomentOfInertiaUnit.DecimeterToTheSixth => baseUnitValue * 1e6, + WarpingMomentOfInertiaUnit.FootToTheSixth => baseUnitValue / Math.Pow(0.3048, 6), + WarpingMomentOfInertiaUnit.InchToTheSixth => baseUnitValue / Math.Pow(2.54e-2, 6), + WarpingMomentOfInertiaUnit.MeterToTheSixth => baseUnitValue, + WarpingMomentOfInertiaUnit.MillimeterToTheSixth => baseUnitValue * 1e18, + _ => throw new NotImplementedException($"Can not convert {Unit} to {unit}.") + }; + } + + #endregion } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Ratio/UnitsNet.NanoFramework.Ratio.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Ratio/UnitsNet.NanoFramework.Ratio.nuspec index c95806e0f2..337563c346 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Ratio/UnitsNet.NanoFramework.Ratio.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Ratio/UnitsNet.NanoFramework.Ratio.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Ratio - 4.149.0 + 5.0.0-alpha006 Units.NET Ratio - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component ratio + nanoframework ratio unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/RatioChangeRate/UnitsNet.NanoFramework.RatioChangeRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/RatioChangeRate/UnitsNet.NanoFramework.RatioChangeRate.nuspec index f987c8a76b..39e9e02671 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/RatioChangeRate/UnitsNet.NanoFramework.RatioChangeRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/RatioChangeRate/UnitsNet.NanoFramework.RatioChangeRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.RatioChangeRate - 4.149.0 + 5.0.0-alpha006 Units.NET RatioChangeRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component ratiochangerate + nanoframework ratiochangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ReactiveEnergy/UnitsNet.NanoFramework.ReactiveEnergy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ReactiveEnergy/UnitsNet.NanoFramework.ReactiveEnergy.nuspec index e93592ffdf..c1978ea296 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ReactiveEnergy/UnitsNet.NanoFramework.ReactiveEnergy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ReactiveEnergy/UnitsNet.NanoFramework.ReactiveEnergy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ReactiveEnergy - 4.149.0 + 5.0.0-alpha006 Units.NET ReactiveEnergy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component reactiveenergy + nanoframework reactiveenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ReactivePower/UnitsNet.NanoFramework.ReactivePower.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ReactivePower/UnitsNet.NanoFramework.ReactivePower.nuspec index f871c0bc9a..598bbb35a2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ReactivePower/UnitsNet.NanoFramework.ReactivePower.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ReactivePower/UnitsNet.NanoFramework.ReactivePower.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ReactivePower - 4.149.0 + 5.0.0-alpha006 Units.NET ReactivePower - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component reactivepower + nanoframework reactivepower unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ReciprocalArea/UnitsNet.NanoFramework.ReciprocalArea.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ReciprocalArea/UnitsNet.NanoFramework.ReciprocalArea.nuspec index 9e5b08a6fe..28d35c9b77 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ReciprocalArea/UnitsNet.NanoFramework.ReciprocalArea.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ReciprocalArea/UnitsNet.NanoFramework.ReciprocalArea.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ReciprocalArea - 4.149.0 + 5.0.0-alpha006 Units.NET ReciprocalArea - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component reciprocalarea + nanoframework reciprocalarea unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ReciprocalLength/UnitsNet.NanoFramework.ReciprocalLength.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ReciprocalLength/UnitsNet.NanoFramework.ReciprocalLength.nuspec index 4b7984e6ae..ab8e8317d4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ReciprocalLength/UnitsNet.NanoFramework.ReciprocalLength.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ReciprocalLength/UnitsNet.NanoFramework.ReciprocalLength.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ReciprocalLength - 4.149.0 + 5.0.0-alpha006 Units.NET ReciprocalLength - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component reciprocallength + nanoframework reciprocallength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/RelativeHumidity/UnitsNet.NanoFramework.RelativeHumidity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/RelativeHumidity/UnitsNet.NanoFramework.RelativeHumidity.nuspec index b97db6a1ff..c4555fb407 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/RelativeHumidity/UnitsNet.NanoFramework.RelativeHumidity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/RelativeHumidity/UnitsNet.NanoFramework.RelativeHumidity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.RelativeHumidity - 4.149.0 + 5.0.0-alpha006 Units.NET RelativeHumidity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component relativehumidity + nanoframework relativehumidity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/RotationalAcceleration/UnitsNet.NanoFramework.RotationalAcceleration.nuspec b/UnitsNet.NanoFramework/GeneratedCode/RotationalAcceleration/UnitsNet.NanoFramework.RotationalAcceleration.nuspec index 62583df7af..c401e49eba 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/RotationalAcceleration/UnitsNet.NanoFramework.RotationalAcceleration.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/RotationalAcceleration/UnitsNet.NanoFramework.RotationalAcceleration.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.RotationalAcceleration - 4.149.0 + 5.0.0-alpha006 Units.NET RotationalAcceleration - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component rotationalacceleration + nanoframework rotationalacceleration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/RotationalSpeed/UnitsNet.NanoFramework.RotationalSpeed.nuspec b/UnitsNet.NanoFramework/GeneratedCode/RotationalSpeed/UnitsNet.NanoFramework.RotationalSpeed.nuspec index 0358caa1c9..d18b7b5e27 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/RotationalSpeed/UnitsNet.NanoFramework.RotationalSpeed.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/RotationalSpeed/UnitsNet.NanoFramework.RotationalSpeed.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.RotationalSpeed - 4.149.0 + 5.0.0-alpha006 Units.NET RotationalSpeed - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component rotationalspeed + nanoframework rotationalspeed unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffness/UnitsNet.NanoFramework.RotationalStiffness.nuspec b/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffness/UnitsNet.NanoFramework.RotationalStiffness.nuspec index 60d28f2cd0..f77e7444b2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffness/UnitsNet.NanoFramework.RotationalStiffness.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffness/UnitsNet.NanoFramework.RotationalStiffness.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.RotationalStiffness - 4.149.0 + 5.0.0-alpha006 Units.NET RotationalStiffness - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component rotationalstiffness + nanoframework rotationalstiffness unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffnessPerLength/UnitsNet.NanoFramework.RotationalStiffnessPerLength.nuspec b/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffnessPerLength/UnitsNet.NanoFramework.RotationalStiffnessPerLength.nuspec index b51714bc21..6ee561a153 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffnessPerLength/UnitsNet.NanoFramework.RotationalStiffnessPerLength.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/RotationalStiffnessPerLength/UnitsNet.NanoFramework.RotationalStiffnessPerLength.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.RotationalStiffnessPerLength - 4.149.0 + 5.0.0-alpha006 Units.NET RotationalStiffnessPerLength - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component rotationalstiffnessperlength + nanoframework rotationalstiffnessperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Scalar/UnitsNet.NanoFramework.Scalar.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Scalar/UnitsNet.NanoFramework.Scalar.nuspec index 0bb5b3177b..71dad6b5bd 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Scalar/UnitsNet.NanoFramework.Scalar.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Scalar/UnitsNet.NanoFramework.Scalar.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Scalar - 4.149.0 + 5.0.0-alpha006 Units.NET Scalar - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component scalar + nanoframework scalar unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/SolidAngle/UnitsNet.NanoFramework.SolidAngle.nuspec b/UnitsNet.NanoFramework/GeneratedCode/SolidAngle/UnitsNet.NanoFramework.SolidAngle.nuspec index 21d574ae8f..2b42d0c370 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/SolidAngle/UnitsNet.NanoFramework.SolidAngle.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/SolidAngle/UnitsNet.NanoFramework.SolidAngle.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.SolidAngle - 4.149.0 + 5.0.0-alpha006 Units.NET SolidAngle - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component solidangle + nanoframework solidangle unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/SpecificEnergy/UnitsNet.NanoFramework.SpecificEnergy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/SpecificEnergy/UnitsNet.NanoFramework.SpecificEnergy.nuspec index ab5285d24f..e7dd6c06d9 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/SpecificEnergy/UnitsNet.NanoFramework.SpecificEnergy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/SpecificEnergy/UnitsNet.NanoFramework.SpecificEnergy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.SpecificEnergy - 4.149.0 + 5.0.0-alpha006 Units.NET SpecificEnergy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component specificenergy + nanoframework specificenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/SpecificEntropy/UnitsNet.NanoFramework.SpecificEntropy.nuspec b/UnitsNet.NanoFramework/GeneratedCode/SpecificEntropy/UnitsNet.NanoFramework.SpecificEntropy.nuspec index 7e11465f51..d9afab8b74 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/SpecificEntropy/UnitsNet.NanoFramework.SpecificEntropy.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/SpecificEntropy/UnitsNet.NanoFramework.SpecificEntropy.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.SpecificEntropy - 4.149.0 + 5.0.0-alpha006 Units.NET SpecificEntropy - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component specificentropy + nanoframework specificentropy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/SpecificFuelConsumption/UnitsNet.NanoFramework.SpecificFuelConsumption.nuspec b/UnitsNet.NanoFramework/GeneratedCode/SpecificFuelConsumption/UnitsNet.NanoFramework.SpecificFuelConsumption.nuspec index 0974a80fd3..b6e5a3172c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/SpecificFuelConsumption/UnitsNet.NanoFramework.SpecificFuelConsumption.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/SpecificFuelConsumption/UnitsNet.NanoFramework.SpecificFuelConsumption.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.SpecificFuelConsumption - 4.149.0 + 5.0.0-alpha006 Units.NET SpecificFuelConsumption - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component specificfuelconsumption + nanoframework specificfuelconsumption unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/SpecificVolume/UnitsNet.NanoFramework.SpecificVolume.nuspec b/UnitsNet.NanoFramework/GeneratedCode/SpecificVolume/UnitsNet.NanoFramework.SpecificVolume.nuspec index f3a7ae94f4..6db6282380 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/SpecificVolume/UnitsNet.NanoFramework.SpecificVolume.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/SpecificVolume/UnitsNet.NanoFramework.SpecificVolume.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.SpecificVolume - 4.149.0 + 5.0.0-alpha006 Units.NET SpecificVolume - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component specificvolume + nanoframework specificvolume unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/SpecificWeight/UnitsNet.NanoFramework.SpecificWeight.nuspec b/UnitsNet.NanoFramework/GeneratedCode/SpecificWeight/UnitsNet.NanoFramework.SpecificWeight.nuspec index 02f45b481a..d9b569a4e0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/SpecificWeight/UnitsNet.NanoFramework.SpecificWeight.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/SpecificWeight/UnitsNet.NanoFramework.SpecificWeight.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.SpecificWeight - 4.149.0 + 5.0.0-alpha006 Units.NET SpecificWeight - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component specificweight + nanoframework specificweight unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Speed/UnitsNet.NanoFramework.Speed.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Speed/UnitsNet.NanoFramework.Speed.nuspec index 2879b9ba5d..48c083c774 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Speed/UnitsNet.NanoFramework.Speed.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Speed/UnitsNet.NanoFramework.Speed.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Speed - 4.149.0 + 5.0.0-alpha006 Units.NET Speed - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component speed + nanoframework speed unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/StandardVolumeFlow/UnitsNet.NanoFramework.StandardVolumeFlow.nuspec b/UnitsNet.NanoFramework/GeneratedCode/StandardVolumeFlow/UnitsNet.NanoFramework.StandardVolumeFlow.nuspec index 66e43c40ea..976d1fe522 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/StandardVolumeFlow/UnitsNet.NanoFramework.StandardVolumeFlow.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/StandardVolumeFlow/UnitsNet.NanoFramework.StandardVolumeFlow.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.StandardVolumeFlow - 4.149.0 + 5.0.0-alpha006 Units.NET StandardVolumeFlow - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component standardvolumeflow + nanoframework standardvolumeflow unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Temperature/UnitsNet.NanoFramework.Temperature.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Temperature/UnitsNet.NanoFramework.Temperature.nuspec index caa5e8f013..2d7b9ce7e6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Temperature/UnitsNet.NanoFramework.Temperature.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Temperature/UnitsNet.NanoFramework.Temperature.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Temperature - 4.149.0 + 5.0.0-alpha006 Units.NET Temperature - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component temperature + nanoframework temperature unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/TemperatureChangeRate/UnitsNet.NanoFramework.TemperatureChangeRate.nuspec b/UnitsNet.NanoFramework/GeneratedCode/TemperatureChangeRate/UnitsNet.NanoFramework.TemperatureChangeRate.nuspec index 51ffb9b459..68226fe94b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/TemperatureChangeRate/UnitsNet.NanoFramework.TemperatureChangeRate.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/TemperatureChangeRate/UnitsNet.NanoFramework.TemperatureChangeRate.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.TemperatureChangeRate - 4.149.0 + 5.0.0-alpha006 Units.NET TemperatureChangeRate - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component temperaturechangerate + nanoframework temperaturechangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/TemperatureDelta/UnitsNet.NanoFramework.TemperatureDelta.nuspec b/UnitsNet.NanoFramework/GeneratedCode/TemperatureDelta/UnitsNet.NanoFramework.TemperatureDelta.nuspec index 1ab7189ba7..11283b17f8 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/TemperatureDelta/UnitsNet.NanoFramework.TemperatureDelta.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/TemperatureDelta/UnitsNet.NanoFramework.TemperatureDelta.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.TemperatureDelta - 4.149.0 + 5.0.0-alpha006 Units.NET TemperatureDelta - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component temperaturedelta + nanoframework temperaturedelta unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/TemperatureGradient/UnitsNet.NanoFramework.TemperatureGradient.nuspec b/UnitsNet.NanoFramework/GeneratedCode/TemperatureGradient/UnitsNet.NanoFramework.TemperatureGradient.nuspec index c2401149ef..cc8e7bd4eb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/TemperatureGradient/UnitsNet.NanoFramework.TemperatureGradient.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/TemperatureGradient/UnitsNet.NanoFramework.TemperatureGradient.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.TemperatureGradient - 4.149.0 + 5.0.0-alpha006 Units.NET TemperatureGradient - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component temperaturegradient + nanoframework temperaturegradient unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ThermalConductivity/UnitsNet.NanoFramework.ThermalConductivity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ThermalConductivity/UnitsNet.NanoFramework.ThermalConductivity.nuspec index 3c6bb0d6e0..9756892b1b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ThermalConductivity/UnitsNet.NanoFramework.ThermalConductivity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ThermalConductivity/UnitsNet.NanoFramework.ThermalConductivity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ThermalConductivity - 4.149.0 + 5.0.0-alpha006 Units.NET ThermalConductivity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component thermalconductivity + nanoframework thermalconductivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/ThermalResistance/UnitsNet.NanoFramework.ThermalResistance.nuspec b/UnitsNet.NanoFramework/GeneratedCode/ThermalResistance/UnitsNet.NanoFramework.ThermalResistance.nuspec index 9e817b3217..3115a66f26 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/ThermalResistance/UnitsNet.NanoFramework.ThermalResistance.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/ThermalResistance/UnitsNet.NanoFramework.ThermalResistance.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.ThermalResistance - 4.149.0 + 5.0.0-alpha006 Units.NET ThermalResistance - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component thermalresistance + nanoframework thermalresistance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Torque/UnitsNet.NanoFramework.Torque.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Torque/UnitsNet.NanoFramework.Torque.nuspec index 06d85f0ecb..196df51b07 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Torque/UnitsNet.NanoFramework.Torque.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Torque/UnitsNet.NanoFramework.Torque.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Torque - 4.149.0 + 5.0.0-alpha006 Units.NET Torque - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component torque + nanoframework torque unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/TorquePerLength/UnitsNet.NanoFramework.TorquePerLength.nuspec b/UnitsNet.NanoFramework/GeneratedCode/TorquePerLength/UnitsNet.NanoFramework.TorquePerLength.nuspec index 4e83abc815..589ade5328 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/TorquePerLength/UnitsNet.NanoFramework.TorquePerLength.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/TorquePerLength/UnitsNet.NanoFramework.TorquePerLength.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.TorquePerLength - 4.149.0 + 5.0.0-alpha006 Units.NET TorquePerLength - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component torqueperlength + nanoframework torqueperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Turbidity/UnitsNet.NanoFramework.Turbidity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Turbidity/UnitsNet.NanoFramework.Turbidity.nuspec index 60aaebc6d8..5a1ed6d19c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Turbidity/UnitsNet.NanoFramework.Turbidity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Turbidity/UnitsNet.NanoFramework.Turbidity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Turbidity - 4.149.0 + 5.0.0-alpha006 Units.NET Turbidity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component turbidity + nanoframework turbidity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AccelerationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AccelerationUnit.g.cs index 46b76aa052..b4f1c48938 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AccelerationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AccelerationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AccelerationUnit { - Undefined = 0, CentimeterPerSecondSquared = 1, DecimeterPerSecondSquared = 2, FootPerSecondSquared = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs index 0c60a66ce4..e0ce7a5da7 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AmountOfSubstanceUnit { - Undefined = 0, Centimole = 1, CentipoundMole = 2, Decimole = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AmplitudeRatioUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AmplitudeRatioUnit.g.cs index 1e2c42e1c7..97a8d592f6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AmplitudeRatioUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AmplitudeRatioUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AmplitudeRatioUnit { - Undefined = 0, DecibelMicrovolt = 1, DecibelMillivolt = 2, DecibelUnloaded = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AngleUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AngleUnit.g.cs index e506e802d2..20e4ff440e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AngleUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AngleUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AngleUnit { - Undefined = 0, Arcminute = 1, Arcsecond = 2, Centiradian = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentEnergyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentEnergyUnit.g.cs index f070ab2cb8..2a8c1aba5b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentEnergyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ApparentEnergyUnit { - Undefined = 0, KilovoltampereHour = 1, MegavoltampereHour = 2, VoltampereHour = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentPowerUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentPowerUnit.g.cs index 1167dda66c..358388af5f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentPowerUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ApparentPowerUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ApparentPowerUnit { - Undefined = 0, Gigavoltampere = 1, Kilovoltampere = 2, Megavoltampere = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AreaDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AreaDensityUnit.g.cs index 053acbdc48..bacdc7e8f4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AreaDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AreaDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AreaDensityUnit { - Undefined = 0, /// /// Also known as grammage for paper industry. In fiber industry used with abbreviation 'gsm'. diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs index 554a32a8fa..388a130b9d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AreaMomentOfInertiaUnit { - Undefined = 0, CentimeterToTheFourth = 1, DecimeterToTheFourth = 2, FootToTheFourth = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/AreaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/AreaUnit.g.cs index 55077cf9a9..f0320c4e99 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/AreaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/AreaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AreaUnit { - Undefined = 0, Acre = 1, Hectare = 2, SquareCentimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/BitRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/BitRateUnit.g.cs index 2390d38afa..6a3760ef6b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/BitRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/BitRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum BitRateUnit { - Undefined = 0, BitPerSecond = 1, BytePerSecond = 2, ExabitPerSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs index cd1f6a61fb..73c93e2039 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum BrakeSpecificFuelConsumptionUnit { - Undefined = 0, GramPerKiloWattHour = 1, KilogramPerJoule = 2, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/CapacitanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/CapacitanceUnit.g.cs index feaebb42fe..a76cc8f2d8 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/CapacitanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/CapacitanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum CapacitanceUnit { - Undefined = 0, Farad = 1, Kilofarad = 2, Megafarad = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs index eb54f874c2..9b7c73ef86 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum CoefficientOfThermalExpansionUnit { - Undefined = 0, InverseDegreeCelsius = 1, InverseDegreeFahrenheit = 2, InverseKelvin = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/CompressibilityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/CompressibilityUnit.g.cs index a45732e3b2..c272160cf2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/CompressibilityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/CompressibilityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum CompressibilityUnit { - Undefined = 0, InverseAtmosphere = 1, InverseBar = 2, InverseKilopascal = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/DensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/DensityUnit.g.cs index f6bdef8d33..a1c2aaa2d3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/DensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/DensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum DensityUnit { - Undefined = 0, CentigramPerDeciliter = 1, CentigramPerLiter = 2, CentigramPerMilliliter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/DurationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/DurationUnit.g.cs index a328323136..6c6aab7c78 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/DurationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/DurationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum DurationUnit { - Undefined = 0, Day = 1, Hour = 2, JulianYear = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/DynamicViscosityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/DynamicViscosityUnit.g.cs index 9d1a1cde30..607837db48 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/DynamicViscosityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/DynamicViscosityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum DynamicViscosityUnit { - Undefined = 0, Centipoise = 1, MicropascalSecond = 2, MillipascalSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs index b0e4153a7e..622b45de43 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricAdmittanceUnit { - Undefined = 0, Microsiemens = 1, Millisiemens = 2, Nanosiemens = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs index 0ebcd43c0f..05909c9a62 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricChargeDensityUnit { - Undefined = 0, CoulombPerCubicMeter = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeUnit.g.cs index 7f9ef9b551..4fda90bf6f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricChargeUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricChargeUnit { - Undefined = 0, AmpereHour = 1, Coulomb = 2, KiloampereHour = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductanceUnit.g.cs index a02ff6fa3a..7bd2b92711 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricConductanceUnit { - Undefined = 0, Microsiemens = 1, Millisiemens = 2, Siemens = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductivityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductivityUnit.g.cs index 509168d9fd..3bca9b88e6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductivityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricConductivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricConductivityUnit { - Undefined = 0, MicrosiemensPerCentimeter = 6, MillisiemensPerCentimeter = 12, SiemensPerCentimeter = 13, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs index 850c97a9af..433e70c970 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricCurrentDensityUnit { - Undefined = 0, AmperePerSquareFoot = 1, AmperePerSquareInch = 2, AmperePerSquareMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs index f6ab790687..eb247e6cfc 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricCurrentGradientUnit { - Undefined = 0, AmperePerMicrosecond = 1, AmperePerMillisecond = 2, AmperePerNanosecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentUnit.g.cs index fd5b0f23f5..8ddd75ca00 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricCurrentUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricCurrentUnit { - Undefined = 0, Ampere = 1, Centiampere = 2, Kiloampere = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricFieldUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricFieldUnit.g.cs index 2aa0e2989f..03ac0494d0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricFieldUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricFieldUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricFieldUnit { - Undefined = 0, VoltPerMeter = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricInductanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricInductanceUnit.g.cs index 41e2121f34..38e85791db 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricInductanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricInductanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricInductanceUnit { - Undefined = 0, Henry = 1, Microhenry = 2, Millihenry = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs index bdb5086350..ada8068172 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialAcUnit { - Undefined = 0, KilovoltAc = 1, MegavoltAc = 2, MicrovoltAc = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs index 3f634b07bf..cac18f9c78 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialChangeRateUnit { - Undefined = 0, KilovoltPerHour = 1, KilovoltPerMicrosecond = 2, KilovoltPerMinute = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs index 05fb4fdd53..224c9c4c30 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialDcUnit { - Undefined = 0, KilovoltDc = 1, MegavoltDc = 2, MicrovoltDc = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialUnit.g.cs index 6540697325..187e8bb192 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricPotentialUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialUnit { - Undefined = 0, Kilovolt = 1, Megavolt = 2, Microvolt = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistanceUnit.g.cs index 31c307e4b6..3852120742 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricResistanceUnit { - Undefined = 0, Gigaohm = 1, Kiloohm = 2, Megaohm = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistivityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistivityUnit.g.cs index 2408b4c477..c7f43cfc6c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistivityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricResistivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricResistivityUnit { - Undefined = 0, KiloohmCentimeter = 1, KiloohmMeter = 2, MegaohmCentimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs index 7fc4d00624..30c7a098de 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricSurfaceChargeDensityUnit { - Undefined = 0, CoulombPerSquareCentimeter = 1, CoulombPerSquareInch = 2, CoulombPerSquareMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyDensityUnit.g.cs index b460210e4b..bf72f7d4f3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum EnergyDensityUnit { - Undefined = 0, GigajoulePerCubicMeter = 6, GigawattHourPerCubicMeter = 8, JoulePerCubicMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyUnit.g.cs index c456440c83..2e8dd78935 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/EnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum EnergyUnit { - Undefined = 0, BritishThermalUnit = 1, Calorie = 2, DecathermEc = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/EntropyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/EntropyUnit.g.cs index b344a123b0..1fbd647e03 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/EntropyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/EntropyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum EntropyUnit { - Undefined = 0, CaloriePerKelvin = 1, JoulePerDegreeCelsius = 2, JoulePerKelvin = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ForceChangeRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ForceChangeRateUnit.g.cs index b45d8f37bf..9b76b2f23a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ForceChangeRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ForceChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ForceChangeRateUnit { - Undefined = 0, CentinewtonPerSecond = 1, DecanewtonPerMinute = 2, DecanewtonPerSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ForcePerLengthUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ForcePerLengthUnit.g.cs index 198215708c..7f6a376ca3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ForcePerLengthUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ForcePerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ForcePerLengthUnit { - Undefined = 0, CentinewtonPerCentimeter = 1, CentinewtonPerMeter = 2, CentinewtonPerMillimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ForceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ForceUnit.g.cs index ace80b3d9f..107e6ae7e4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ForceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ForceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ForceUnit { - Undefined = 0, Decanewton = 1, Dyn = 2, KilogramForce = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/FrequencyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/FrequencyUnit.g.cs index 937416774a..c78283ce9c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/FrequencyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/FrequencyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum FrequencyUnit { - Undefined = 0, BeatPerMinute = 1, BUnit = 2, CyclePerHour = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/FuelEfficiencyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/FuelEfficiencyUnit.g.cs index 603d4f60c4..24491dee95 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/FuelEfficiencyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/FuelEfficiencyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum FuelEfficiencyUnit { - Undefined = 0, KilometerPerLiter = 1, LiterPer100Kilometers = 2, MilePerUkGallon = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/HeatFluxUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/HeatFluxUnit.g.cs index 343ac00a17..a03b4d90e6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/HeatFluxUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/HeatFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum HeatFluxUnit { - Undefined = 0, BtuPerHourSquareFoot = 1, BtuPerMinuteSquareFoot = 2, BtuPerSecondSquareFoot = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs index 612f5fd15d..e337b5095a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum HeatTransferCoefficientUnit { - Undefined = 0, BtuPerSquareFootDegreeFahrenheit = 1, WattPerSquareMeterCelsius = 2, WattPerSquareMeterKelvin = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/IlluminanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/IlluminanceUnit.g.cs index 2884dbc49f..7675a53867 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/IlluminanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/IlluminanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum IlluminanceUnit { - Undefined = 0, Kilolux = 1, Lux = 2, Megalux = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/InformationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/InformationUnit.g.cs index c9f39a1851..fd72b621c2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/InformationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/InformationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum InformationUnit { - Undefined = 0, Bit = 1, Byte = 2, Exabit = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/IrradianceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/IrradianceUnit.g.cs index 953dc136c2..2ed5f09b06 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/IrradianceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/IrradianceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum IrradianceUnit { - Undefined = 0, KilowattPerSquareCentimeter = 1, KilowattPerSquareMeter = 2, MegawattPerSquareCentimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/IrradiationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/IrradiationUnit.g.cs index a3890297b3..449fdf2491 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/IrradiationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/IrradiationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum IrradiationUnit { - Undefined = 0, JoulePerSquareCentimeter = 1, JoulePerSquareMeter = 2, JoulePerSquareMillimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/JerkUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/JerkUnit.g.cs index 1c33b996c1..e269a35497 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/JerkUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/JerkUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum JerkUnit { - Undefined = 0, CentimeterPerSecondCubed = 1, DecimeterPerSecondCubed = 2, FootPerSecondCubed = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/KinematicViscosityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/KinematicViscosityUnit.g.cs index a834ca556c..f01709d0c3 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/KinematicViscosityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/KinematicViscosityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum KinematicViscosityUnit { - Undefined = 0, Centistokes = 1, Decistokes = 2, Kilostokes = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LapseRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LapseRateUnit.g.cs index cdc802a5fe..b6be109fd4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LapseRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LapseRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LapseRateUnit { - Undefined = 0, DegreeCelsiusPerKilometer = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LengthUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LengthUnit.g.cs index 613a0a4f54..3c8459608b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LengthUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LengthUnit { - Undefined = 0, /// /// Angstrom is a metric unit of length equal to 1e-10 meter diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LevelUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LevelUnit.g.cs index 7ae6a7f7b3..3d1966d2b2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LevelUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LevelUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LevelUnit { - Undefined = 0, Decibel = 1, Neper = 2, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LinearDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LinearDensityUnit.g.cs index e2135b4248..652bf6b524 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LinearDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LinearDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LinearDensityUnit { - Undefined = 0, GramPerCentimeter = 1, GramPerMeter = 2, GramPerMillimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LinearPowerDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LinearPowerDensityUnit.g.cs index a75b9242b3..2ab6e250ac 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LinearPowerDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LinearPowerDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LinearPowerDensityUnit { - Undefined = 0, GigawattPerCentimeter = 1, GigawattPerFoot = 2, GigawattPerInch = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminanceUnit.g.cs index 0bb831b042..24814e4dcc 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminanceUnit { - Undefined = 0, CandelaPerSquareFoot = 10, CandelaPerSquareInch = 7, CandelaPerSquareMeter = 8, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminosityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminosityUnit.g.cs index e67ff7eaf2..44cdfec58c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminosityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminosityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminosityUnit { - Undefined = 0, Decawatt = 1, Deciwatt = 2, Femtowatt = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousFluxUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousFluxUnit.g.cs index 1feaa278db..01a956a02c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousFluxUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminousFluxUnit { - Undefined = 0, Lumen = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousIntensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousIntensityUnit.g.cs index a274ff66bb..947d36fb22 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousIntensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/LuminousIntensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminousIntensityUnit { - Undefined = 0, Candela = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFieldUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFieldUnit.g.cs index fea90267d8..3915ff523d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFieldUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFieldUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MagneticFieldUnit { - Undefined = 0, Gauss = 1, Microtesla = 2, Milligauss = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFluxUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFluxUnit.g.cs index 01b2a98881..e7f3635d2e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFluxUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MagneticFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MagneticFluxUnit { - Undefined = 0, Weber = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MagnetizationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MagnetizationUnit.g.cs index b0cad1d3ee..956c88e2da 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MagnetizationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MagnetizationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MagnetizationUnit { - Undefined = 0, AmperePerMeter = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MassConcentrationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MassConcentrationUnit.g.cs index 300abb73f1..e80ca6a945 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MassConcentrationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MassConcentrationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassConcentrationUnit { - Undefined = 0, CentigramPerDeciliter = 1, CentigramPerLiter = 2, CentigramPerMicroliter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MassFlowUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MassFlowUnit.g.cs index 05e7a1bda4..7df77cf7b5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MassFlowUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MassFlowUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassFlowUnit { - Undefined = 0, CentigramPerDay = 1, CentigramPerSecond = 2, DecagramPerDay = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MassFluxUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MassFluxUnit.g.cs index 35e800eb11..def9d86acb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MassFluxUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MassFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassFluxUnit { - Undefined = 0, GramPerHourPerSquareCentimeter = 1, GramPerHourPerSquareMeter = 2, GramPerHourPerSquareMillimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MassFractionUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MassFractionUnit.g.cs index f739fe0ed9..0dad8a059f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MassFractionUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MassFractionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassFractionUnit { - Undefined = 0, CentigramPerGram = 1, CentigramPerKilogram = 2, DecagramPerGram = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs index 7fac42d9f7..33c92670cb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassMomentOfInertiaUnit { - Undefined = 0, GramSquareCentimeter = 1, GramSquareDecimeter = 2, GramSquareMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MassUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MassUnit.g.cs index b88ff4ffea..5cf1e962b4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MassUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MassUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassUnit { - Undefined = 0, Centigram = 1, Decagram = 2, Decigram = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEnergyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEnergyUnit.g.cs index 71c6f75ae5..71772f28ea 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEnergyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarEnergyUnit { - Undefined = 0, JoulePerMole = 1, KilojoulePerMole = 2, MegajoulePerMole = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEntropyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEntropyUnit.g.cs index d0db13e9e6..b7e6c5aa56 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEntropyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarEntropyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarEntropyUnit { - Undefined = 0, JoulePerMoleKelvin = 1, KilojoulePerMoleKelvin = 2, MegajoulePerMoleKelvin = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarMassUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarMassUnit.g.cs index 11fa8ae422..417075c855 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarMassUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarMassUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarMassUnit { - Undefined = 0, CentigramPerMole = 1, DecagramPerMole = 2, DecigramPerMole = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarityUnit.g.cs index 0ece495fca..3d914b3836 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/MolarityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/MolarityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarityUnit { - Undefined = 0, CentimolePerLiter = 1, [System.Obsolete("Use the singular unit instead.")] CentimolesPerLiter = 2, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PermeabilityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PermeabilityUnit.g.cs index 0201d80052..19860cb22a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PermeabilityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PermeabilityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PermeabilityUnit { - Undefined = 0, HenryPerMeter = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PermittivityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PermittivityUnit.g.cs index 1409a5302a..77e869b6fe 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PermittivityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PermittivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PermittivityUnit { - Undefined = 0, FaradPerMeter = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs index a50e0e2309..9b57db7199 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PorousMediumPermeabilityUnit { - Undefined = 0, Darcy = 1, Microdarcy = 2, Millidarcy = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PowerDensityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PowerDensityUnit.g.cs index 8ee2c0fdf2..74a52d1da5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PowerDensityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PowerDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PowerDensityUnit { - Undefined = 0, DecawattPerCubicFoot = 1, DecawattPerCubicInch = 2, DecawattPerCubicMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PowerRatioUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PowerRatioUnit.g.cs index cb3e453996..f0c4dc508c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PowerRatioUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PowerRatioUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PowerRatioUnit { - Undefined = 0, DecibelMilliwatt = 1, DecibelWatt = 2, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PowerUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PowerUnit.g.cs index 6cbbd7bea0..303f690f6e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PowerUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PowerUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PowerUnit { - Undefined = 0, BoilerHorsepower = 1, BritishThermalUnitPerHour = 2, Decawatt = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PressureChangeRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PressureChangeRateUnit.g.cs index da273f2fba..fed99a6a4a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PressureChangeRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PressureChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PressureChangeRateUnit { - Undefined = 0, AtmospherePerSecond = 1, KilopascalPerMinute = 2, KilopascalPerSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/PressureUnit.g.cs index 49d9287d09..5d832b88b1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/PressureUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/PressureUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PressureUnit { - Undefined = 0, Atmosphere = 1, Bar = 2, Centibar = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RatioChangeRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RatioChangeRateUnit.g.cs index 56b777fd88..8537a14a05 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RatioChangeRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RatioChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RatioChangeRateUnit { - Undefined = 0, DecimalFractionPerSecond = 1, PercentPerSecond = 2, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RatioUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RatioUnit.g.cs index b60a692b6f..32a4540bc5 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RatioUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RatioUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RatioUnit { - Undefined = 0, DecimalFraction = 1, PartPerBillion = 2, PartPerMillion = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ReactiveEnergyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ReactiveEnergyUnit.g.cs index 215987924b..d48f6482a1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ReactiveEnergyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ReactiveEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReactiveEnergyUnit { - Undefined = 0, KilovoltampereReactiveHour = 1, MegavoltampereReactiveHour = 2, VoltampereReactiveHour = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ReactivePowerUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ReactivePowerUnit.g.cs index 1bdbcb0121..32e7a9ede9 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ReactivePowerUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ReactivePowerUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReactivePowerUnit { - Undefined = 0, GigavoltampereReactive = 1, KilovoltampereReactive = 2, MegavoltampereReactive = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalAreaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalAreaUnit.g.cs index d4f2593f92..a1263b27b9 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalAreaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalAreaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReciprocalAreaUnit { - Undefined = 0, InverseSquareCentimeter = 1, InverseSquareDecimeter = 2, InverseSquareFoot = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalLengthUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalLengthUnit.g.cs index 3ccd608f92..fb9d93700c 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalLengthUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ReciprocalLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReciprocalLengthUnit { - Undefined = 0, InverseCentimeter = 1, InverseFoot = 2, InverseInch = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RelativeHumidityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RelativeHumidityUnit.g.cs index c88fbf8d1e..5962021a21 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RelativeHumidityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RelativeHumidityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RelativeHumidityUnit { - Undefined = 0, Percent = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalAccelerationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalAccelerationUnit.g.cs index 9ddbefc178..78d18c4ea1 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalAccelerationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalAccelerationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalAccelerationUnit { - Undefined = 0, DegreePerSecondSquared = 1, RadianPerSecondSquared = 2, RevolutionPerMinutePerSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalSpeedUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalSpeedUnit.g.cs index 9e32344eb3..c764514ede 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalSpeedUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalSpeedUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalSpeedUnit { - Undefined = 0, CentiradianPerSecond = 1, DeciradianPerSecond = 2, DegreePerMinute = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs index efc7959875..3829297d44 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalStiffnessPerLengthUnit { - Undefined = 0, KilonewtonMeterPerRadianPerMeter = 1, KilopoundForceFootPerDegreesPerFoot = 2, MeganewtonMeterPerRadianPerMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessUnit.g.cs index f776cbb8f9..6905f8d976 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/RotationalStiffnessUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalStiffnessUnit { - Undefined = 0, CentinewtonMeterPerDegree = 1, CentinewtonMillimeterPerDegree = 2, CentinewtonMillimeterPerRadian = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ScalarUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ScalarUnit.g.cs index 45affd9a84..c8be591b38 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ScalarUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ScalarUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ScalarUnit { - Undefined = 0, Amount = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SolidAngleUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SolidAngleUnit.g.cs index 7b4106c8a6..7be81ae1a0 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SolidAngleUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SolidAngleUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SolidAngleUnit { - Undefined = 0, Steradian = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEnergyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEnergyUnit.g.cs index 32a6eb19a1..85d8161f49 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEnergyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificEnergyUnit { - Undefined = 0, BtuPerPound = 1, CaloriePerGram = 2, GigawattDayPerKilogram = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEntropyUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEntropyUnit.g.cs index 4dd42087c0..77e55a2af2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEntropyUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificEntropyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificEntropyUnit { - Undefined = 0, BtuPerPoundFahrenheit = 1, CaloriePerGramKelvin = 2, JoulePerKilogramDegreeCelsius = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs index 45720475d3..f647a17cf6 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificFuelConsumptionUnit { - Undefined = 0, GramPerKiloNewtonSecond = 1, KilogramPerKilogramForceHour = 2, KilogramPerKiloNewtonSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificVolumeUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificVolumeUnit.g.cs index 12a7cb9117..49be37c632 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificVolumeUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificVolumeUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificVolumeUnit { - Undefined = 0, CubicFootPerPound = 1, CubicMeterPerKilogram = 2, MillicubicMeterPerKilogram = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificWeightUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificWeightUnit.g.cs index dbd7987dc9..a4ff736200 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificWeightUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SpecificWeightUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificWeightUnit { - Undefined = 0, KilogramForcePerCubicCentimeter = 1, KilogramForcePerCubicMeter = 2, KilogramForcePerCubicMillimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/SpeedUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/SpeedUnit.g.cs index 3a8028b74c..4910d16b5d 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/SpeedUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/SpeedUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpeedUnit { - Undefined = 0, CentimeterPerHour = 1, CentimeterPerMinute = 2, CentimeterPerSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs index ea5508eeef..212589934b 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum StandardVolumeFlowUnit { - Undefined = 0, StandardCubicCentimeterPerMinute = 1, StandardCubicFootPerHour = 2, StandardCubicFootPerMinute = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs index cfdf7c7aae..b06ed41185 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureChangeRateUnit { - Undefined = 0, CentidegreeCelsiusPerSecond = 1, DecadegreeCelsiusPerSecond = 2, DecidegreeCelsiusPerSecond = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureDeltaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureDeltaUnit.g.cs index 2c14e83a45..7895e204a4 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureDeltaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureDeltaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureDeltaUnit { - Undefined = 0, DegreeCelsius = 1, DegreeDelisle = 2, DegreeFahrenheit = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureGradientUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureGradientUnit.g.cs index b0899dc22f..73040b84a2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureGradientUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureGradientUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureGradientUnit { - Undefined = 0, DegreeCelsiusPerKilometer = 1, DegreeCelsiusPerMeter = 2, DegreeFahrenheitPerFoot = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureUnit.g.cs index 2f0f9a6659..51a02d8902 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TemperatureUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureUnit { - Undefined = 0, DegreeCelsius = 1, DegreeDelisle = 2, DegreeFahrenheit = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalConductivityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalConductivityUnit.g.cs index 42dd7659be..044fda144e 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalConductivityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalConductivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ThermalConductivityUnit { - Undefined = 0, BtuPerHourFootFahrenheit = 1, WattPerMeterKelvin = 2, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalResistanceUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalResistanceUnit.g.cs index 94b9ab1ea3..3fdcc10310 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalResistanceUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/ThermalResistanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ThermalResistanceUnit { - Undefined = 0, HourSquareFeetDegreeFahrenheitPerBtu = 1, SquareCentimeterHourDegreeCelsiusPerKilocalorie = 2, SquareCentimeterKelvinPerWatt = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TorquePerLengthUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TorquePerLengthUnit.g.cs index 2b12da6fb9..4145084d80 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TorquePerLengthUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TorquePerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TorquePerLengthUnit { - Undefined = 0, KilogramForceCentimeterPerMeter = 1, KilogramForceMeterPerMeter = 2, KilogramForceMillimeterPerMeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TorqueUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TorqueUnit.g.cs index 581342ee11..74ad9eb231 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TorqueUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TorqueUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TorqueUnit { - Undefined = 0, GramForceCentimeter = 1, GramForceMeter = 2, GramForceMillimeter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/TurbidityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/TurbidityUnit.g.cs index 85a2938a39..a511c7c143 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/TurbidityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/TurbidityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TurbidityUnit { - Undefined = 0, NTU = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VitaminAUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VitaminAUnit.g.cs index 79cad5b3a5..2ffecd0c47 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VitaminAUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VitaminAUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VitaminAUnit { - Undefined = 0, InternationalUnit = 1, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeConcentrationUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeConcentrationUnit.g.cs index b4bd03a032..b60c944f4a 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeConcentrationUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeConcentrationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeConcentrationUnit { - Undefined = 0, CentilitersPerLiter = 1, CentilitersPerMililiter = 2, DecilitersPerLiter = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs index 547df05f54..abcdea8f8f 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeFlowPerAreaUnit { - Undefined = 0, CubicFootPerMinutePerSquareFoot = 1, CubicMeterPerSecondPerSquareMeter = 2, } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowUnit.g.cs index 9e6052fd34..08291ef5da 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeFlowUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeFlowUnit { - Undefined = 0, AcreFootPerDay = 1, AcreFootPerHour = 2, AcreFootPerMinute = 3, @@ -71,7 +70,7 @@ public enum VolumeFlowUnit MilliliterPerHour = 43, MilliliterPerMinute = 44, MilliliterPerSecond = 45, - MillionUsGallonsPerDay = 46, + MillionUsGallonPerDay = 66, NanoliterPerDay = 47, NanoliterPerHour = 48, NanoliterPerMinute = 49, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumePerLengthUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumePerLengthUnit.g.cs index 25ee46d602..73b3ab5b35 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumePerLengthUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumePerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumePerLengthUnit { - Undefined = 0, CubicMeterPerMeter = 1, CubicYardPerFoot = 2, CubicYardPerUsSurveyFoot = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeUnit.g.cs index 0af0456cc6..110a0a1d55 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumeUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeUnit { - Undefined = 0, AcreFoot = 1, AuTablespoon = 2, BoardFoot = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs index c0a9c09dac..e3fb1141fb 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumetricHeatCapacityUnit { - Undefined = 0, BtuPerCubicFootDegreeFahrenheit = 1, CaloriePerCubicCentimeterDegreeCelsius = 2, JoulePerCubicMeterDegreeCelsius = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs index 1bb269933a..5f77a6d521 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum WarpingMomentOfInertiaUnit { - Undefined = 0, CentimeterToTheSixth = 1, DecimeterToTheSixth = 2, FootToTheSixth = 3, diff --git a/UnitsNet.NanoFramework/GeneratedCode/VitaminA/UnitsNet.NanoFramework.VitaminA.nuspec b/UnitsNet.NanoFramework/GeneratedCode/VitaminA/UnitsNet.NanoFramework.VitaminA.nuspec index ea023a595f..b8756009cf 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/VitaminA/UnitsNet.NanoFramework.VitaminA.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/VitaminA/UnitsNet.NanoFramework.VitaminA.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.VitaminA - 4.149.0 + 5.0.0-alpha006 Units.NET VitaminA - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component vitamina + nanoframework vitamina unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/Volume/UnitsNet.NanoFramework.Volume.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Volume/UnitsNet.NanoFramework.Volume.nuspec index 6dd901f077..6fa4857d84 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Volume/UnitsNet.NanoFramework.Volume.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/Volume/UnitsNet.NanoFramework.Volume.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.Volume - 4.149.0 + 5.0.0-alpha006 Units.NET Volume - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component volume + nanoframework volume unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/VolumeConcentration/UnitsNet.NanoFramework.VolumeConcentration.nuspec b/UnitsNet.NanoFramework/GeneratedCode/VolumeConcentration/UnitsNet.NanoFramework.VolumeConcentration.nuspec index 083b402013..38905744ac 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/VolumeConcentration/UnitsNet.NanoFramework.VolumeConcentration.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/VolumeConcentration/UnitsNet.NanoFramework.VolumeConcentration.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.VolumeConcentration - 4.149.0 + 5.0.0-alpha006 Units.NET VolumeConcentration - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component volumeconcentration + nanoframework volumeconcentration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/VolumeFlow/UnitsNet.NanoFramework.VolumeFlow.nuspec b/UnitsNet.NanoFramework/GeneratedCode/VolumeFlow/UnitsNet.NanoFramework.VolumeFlow.nuspec index 8b1dd56773..d8a477b581 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/VolumeFlow/UnitsNet.NanoFramework.VolumeFlow.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/VolumeFlow/UnitsNet.NanoFramework.VolumeFlow.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.VolumeFlow - 4.149.0 + 5.0.0-alpha006 Units.NET VolumeFlow - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component volumeflow + nanoframework volumeflow unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/VolumeFlowPerArea/UnitsNet.NanoFramework.VolumeFlowPerArea.nuspec b/UnitsNet.NanoFramework/GeneratedCode/VolumeFlowPerArea/UnitsNet.NanoFramework.VolumeFlowPerArea.nuspec index a76fcf2442..67e12a7426 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/VolumeFlowPerArea/UnitsNet.NanoFramework.VolumeFlowPerArea.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/VolumeFlowPerArea/UnitsNet.NanoFramework.VolumeFlowPerArea.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.VolumeFlowPerArea - 4.149.0 + 5.0.0-alpha006 Units.NET VolumeFlowPerArea - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component volumeflowperarea + nanoframework volumeflowperarea unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/VolumePerLength/UnitsNet.NanoFramework.VolumePerLength.nuspec b/UnitsNet.NanoFramework/GeneratedCode/VolumePerLength/UnitsNet.NanoFramework.VolumePerLength.nuspec index f342e276ed..ff83aee088 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/VolumePerLength/UnitsNet.NanoFramework.VolumePerLength.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/VolumePerLength/UnitsNet.NanoFramework.VolumePerLength.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.VolumePerLength - 4.149.0 + 5.0.0-alpha006 Units.NET VolumePerLength - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component volumeperlength + nanoframework volumeperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/VolumetricHeatCapacity/UnitsNet.NanoFramework.VolumetricHeatCapacity.nuspec b/UnitsNet.NanoFramework/GeneratedCode/VolumetricHeatCapacity/UnitsNet.NanoFramework.VolumetricHeatCapacity.nuspec index a67173b6e0..4c45a39ada 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/VolumetricHeatCapacity/UnitsNet.NanoFramework.VolumetricHeatCapacity.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/VolumetricHeatCapacity/UnitsNet.NanoFramework.VolumetricHeatCapacity.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.VolumetricHeatCapacity - 4.149.0 + 5.0.0-alpha006 Units.NET VolumetricHeatCapacity - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component volumetricheatcapacity + nanoframework volumetricheatcapacity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NanoFramework/GeneratedCode/WarpingMomentOfInertia/UnitsNet.NanoFramework.WarpingMomentOfInertia.nuspec b/UnitsNet.NanoFramework/GeneratedCode/WarpingMomentOfInertia/UnitsNet.NanoFramework.WarpingMomentOfInertia.nuspec index 34b1db87d7..7a5f5e4ae2 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/WarpingMomentOfInertia/UnitsNet.NanoFramework.WarpingMomentOfInertia.nuspec +++ b/UnitsNet.NanoFramework/GeneratedCode/WarpingMomentOfInertia/UnitsNet.NanoFramework.WarpingMomentOfInertia.nuspec @@ -2,7 +2,7 @@ UnitsNet.nanoFramework.WarpingMomentOfInertia - 4.149.0 + 5.0.0-alpha006 Units.NET WarpingMomentOfInertia - nanoFramework Andreas Gullberg Larsen,nanoFramework project contributors UnitsNet @@ -15,7 +15,7 @@ Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). en-US - nanoframework unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component warpingmomentofinertia + nanoframework warpingmomentofinertia unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable diff --git a/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj b/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj index 9b6efc6d7a..b07181b8a3 100644 --- a/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj +++ b/UnitsNet.NumberExtensions.Tests/UnitsNet.NumberExtensions.Tests.csproj @@ -1,9 +1,10 @@ - net5.0 + net6.0 UnitsNet.NumberExtensions.Tests latest + enable true diff --git a/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj b/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj index f887fab6e9..331edc0c0b 100644 --- a/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj +++ b/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj @@ -2,7 +2,7 @@ UnitsNet.NumberExtensions - 4.149.0 + 5.0.0-alpha006 Andreas Gullberg Larsen, Lu Li, Jon Suda Units.NET NumberExtensions Adds extension methods to number types to more easily create quantities, such as 5.Meters() instead of Length.FromMeters(5). @@ -18,11 +18,11 @@ - 4.0.0.0 + 5.0.0.0 latest enable UnitsNet - netstandard2.0;net40 + netstandard2.0 diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj deleted file mode 100644 index dd41b781dc..0000000000 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net5.0 - UnitsNet.Serialization.JsonNet.CompatibilityTests - latest - true - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs deleted file mode 100644 index 3a71fbc5fe..0000000000 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs +++ /dev/null @@ -1,464 +0,0 @@ -// Licensed under MIT 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 Newtonsoft.Json; -using Xunit; - -namespace UnitsNet.Serialization.JsonNet.CompatibilityTests -{ - public class UnitsNetJsonConverterTests - { - private readonly JsonSerializerSettings _jsonSerializerSettings; - - protected UnitsNetJsonConverterTests() - { - _jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented}; - _jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - } - - private string SerializeObject(object obj) - { - return JsonConvert.SerializeObject(obj, _jsonSerializerSettings).Replace("\r\n", "\n"); - } - - private T DeserializeObject(string json) - { - return JsonConvert.DeserializeObject(json, _jsonSerializerSettings); - } - - public class Serialize : UnitsNetJsonConverterTests - { - [Fact] - public void Information_CanSerializeVeryLargeValues() - { - Information i = Information.FromExabytes(1E+9); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; - - string json = SerializeObject(i); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void Mass_ExpectConstructedValueAndUnit() - { - Mass mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; - - string json = SerializeObject(mass); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void Information_ExpectConstructedValueAndUnit() - { - Information quantity = Information.FromKilobytes(54); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; - - string json = SerializeObject(quantity); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void NonNullNullableValue_ExpectJsonUnaffected() - { - Mass? nullableMass = Mass.FromKilograms(10); - var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 10.0\n}"; - - string json = SerializeObject(nullableMass); - - // There shouldn't be any change in the JSON for the non-null nullable value. - Assert.Equal(expectedJson, json); - } - - [Fact] - public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() - { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; - // Ugly manually formatted JSON string is used because string literals with newlines are rendered differently - // on the build server (i.e. the build server uses '\r' instead of '\n') - string expectedJson = "{\n" + - " \"NullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " \"NonNullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "}"; - - string json = SerializeObject(testObj); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void NullValue_ExpectJsonContainsNullString() - { - string json = SerializeObject(null); - Assert.Equal("null", json); - } - - [Fact] - public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() - { - Ratio ratio = Ratio.FromPartsPerThousand(250); - var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; - - string json = SerializeObject(ratio); - - Assert.Equal(expectedJson, json); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayValue_ExpectJsonArray() - { - Frequency[] testObj = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - - string expectedJson = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - string json = SerializeObject(testObj); - - Assert.Equal(expectedJson, json); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArrayValue_ExpectJsonArray() - { - Frequency[] testObj = new Frequency[0]; - - string expectedJson = "[]"; - - string json = SerializeObject(testObj); - Assert.Equal(expectedJson, json); - } - } - - public class Deserialize : UnitsNetJsonConverterTests - { - [Fact] - public void Information_CanDeserializeVeryLargeValues() - { - Information original = Information.FromExabytes(1E+9); - string json = SerializeObject(original); - var deserialized = DeserializeObject(json); - - Assert.Equal(original, deserialized); - } - - [Fact] - public void Mass_ExpectJsonCorrectlyDeserialized() - { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); - - var deserializedMass = DeserializeObject(json); - - Assert.Equal(originalMass, deserializedMass); - } - - [Fact] - public void NonNullNullableValue_ExpectValueDeserializedCorrectly() - { - Mass? nullableMass = Mass.FromKilograms(10); - string json = SerializeObject(nullableMass); - - Mass? deserializedNullableMass = DeserializeObject(json); - - Assert.Equal(nullableMass.Value, deserializedNullableMass); - } - - [Fact] - public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly() - { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); - - var deserializedTestObj = DeserializeObject(json); - - Assert.Equal(testObj.NullableFrequency, deserializedTestObj.NullableFrequency); - } - - [Fact] - public void NullValue_ExpectNullReturned() - { - string json = SerializeObject(null); - var deserializedNullMass = DeserializeObject(json); - - Assert.Null(deserializedNullMass); - } - - [Fact] - public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly() - { - var testObj = new TestObj - { - NullableFrequency = null, - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); - - var deserializedTestObj = DeserializeObject(json); - - Assert.Null(deserializedTestObj.NullableFrequency); - } - - [Fact] - public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() - { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); - // Someone manually changed the serialized JSON string to 1000 grams. - json = json.Replace("33.33", "1000"); - json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); - - var deserializedMass = DeserializeObject(json); - - // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is - // still deserializable, and the correct value of 1000 g is obtained. - Assert.Equal(1000, deserializedMass.Grams); - } - - [Fact] - public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = Power.FromWatts(10) - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json,jsonSerializerSettings); - - Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); - Assert.Equal(Power.FromWatts(10), (Power)deserializedTestObject.Value); - } - - [Fact] - public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = 10.0 - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, (double)deserializedTestObject.Value); - } - - [Fact] - public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = new ComparableClass() { Value = 10 } - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); - } - - [Fact] - public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() - { - TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit() - { - Value = 5, - Unit = "Test", - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); - TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(5d, deserializedTestObject.Value); - Assert.Equal("Test", deserializedTestObject.Unit); - } - - [Fact] - public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized() - { - TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable() - { - Value1 = 10.0, - Value2 = Power.FromWatts(19), - Value3 = new ComparableClass() { Value = 10 }, - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value1.GetType()); - Assert.Equal(10d, deserializedTestObject.Value1); - Assert.Equal(typeof(Power), deserializedTestObject.Value2.GetType()); - Assert.Equal(Power.FromWatts(19), deserializedTestObject.Value2); - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value3.GetType()); - Assert.Equal(testObjWithIComparable.Value3, deserializedTestObject.Value3); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayOfUnits_ExpectCorrectlyDeserialized() - { - Frequency[] expected = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - - string json = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - Frequency[] result = DeserializeObject(json); - - Assert.Equal(expected, result); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void MultiDimArrayOfUnits_ExpectCorrectlyDeserialized() - { - Frequency[,] expected = { { Frequency.FromHertz(10), Frequency.FromHertz(10) }, { Frequency.FromHertz(10), Frequency.FromHertz(10) } }; - - string json = "[\n" + - " [\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - " ],\n" + - " [\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - " ]\n" + - "]"; - - Frequency[,] result = DeserializeObject(json); - - Assert.Equal(expected, result); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArray_ExpectCorrectlyDeserialized() - { - string json = "[]"; - - Frequency[] result = DeserializeObject(json); - - Assert.Empty(result); - } - - private static JsonSerializerSettings CreateJsonSerializerSettings() - { - var jsonSerializerSettings = new JsonSerializerSettings() - { - Formatting = Formatting.Indented, - TypeNameHandling = TypeNameHandling.Auto - }; - jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - return jsonSerializerSettings; - } - } - - private class TestObj - { - public Frequency? NullableFrequency { get; set; } - public Frequency NonNullableFrequency { get; set; } - } - - private class TestObjWithValueAndUnit : IComparable - { - public double Value { get; set; } - public string Unit { get; set; } - - public int CompareTo(object obj) - { - return ((IComparable)Value).CompareTo(obj); - } - } - - private class ComparableClass : IComparable - { - public int Value { get; set; } - public int CompareTo(object obj) - { - return ((IComparable)Value).CompareTo(obj); - } - - // Needed for virfying that the deserialized object is the same, should not affect the serilization code - public override bool Equals(object obj) - { - if (obj == null || GetType() != obj.GetType()) - { - return false; - } - return Value.Equals(((ComparableClass)obj).Value); - } - - public override int GetHashCode() - { - return Value.GetHashCode(); - } - } - - private class TestObjWithIComparable - { - public IComparable Value { get; set; } - } - - private class TestObjWithThreeIComparable - { - public IComparable Value1 { get; set; } - - public IComparable Value2 { get; set; } - - public IComparable Value3 { get; set; } - } - } -} diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index 96da9bbaf5..ba0972cf84 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -1,7 +1,7 @@  - net5.0 + net6.0 UnitsNet.Serialization.JsonNet.Tests latest true diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs index 2e88dc6d9e..76e82be109 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs @@ -54,18 +54,10 @@ public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.True(Power.FromWatts(10.2365m).Equals((Power)result, 1E-5, ComparisonType.Absolute)); + Assert.True(Power.FromWatts(10.2365m).Equals((Power)result, 1E-5m, ComparisonType.Absolute)); } - [Fact] - public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_with_NULL_value() - { - var result = _sut.Test_ConvertValueUnit(); - - Assert.Null(result); - } - [Fact] public void UnitsNetBaseJsonConverter_ConvertValueUnit_throws_UnitsNetException_when_unit_does_not_exist() { @@ -157,7 +149,6 @@ public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_value_type Assert.Null(result); } - [Fact] public void UnitsNetBaseJsonConverter_ReadDoubleValueUnit_works_with_empty_token() { @@ -210,7 +201,6 @@ public void UnitsNetBaseJsonConverter_ReadValueUnit_works_case_insensitive( {valueTypePropertyName, "decimal"} }; - var result = _sut.Test_ReadDecimalValueUnit(token); Assert.NotNull(result); diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs index f8053607da..bbe5522852 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs @@ -117,7 +117,7 @@ public void UnitsNetIComparableJsonConverter_ReadJson_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.Equal(120D, ((Power)result).Watts); + Assert.Equal(120M, ((Power)result).Watts); } } } diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs index 56341bce15..8ed7de7c29 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; @@ -13,7 +12,7 @@ namespace UnitsNet.Serialization.JsonNet.Tests { public sealed class UnitsNetIQuantityJsonConverterTest { - private UnitsNetIQuantityJsonConverter _sut; + private readonly UnitsNetIQuantityJsonConverter _sut; public UnitsNetIQuantityJsonConverterTest() { @@ -136,7 +135,7 @@ public void UnitsNetIQuantityJsonConverter_ReadJson_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.Equal(10.3654D, ((Power)result).Watts); + Assert.Equal(10.3654M, ((Power)result).Watts); } } } diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonDeserializationTests.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonDeserializationTests.cs index f789666e18..7a3f331ce4 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonDeserializationTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonDeserializationTests.cs @@ -1,8 +1,10 @@ // Licensed under MIT 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 Newtonsoft.Json; using UnitsNet.Serialization.JsonNet.Tests.Infrastructure; +using UnitsNet.Units; using Xunit; namespace UnitsNet.Serialization.JsonNet.Tests @@ -10,9 +12,9 @@ namespace UnitsNet.Serialization.JsonNet.Tests public sealed class UnitsNetJsonDeserializationTests : UnitsNetJsonBaseTest { [Fact] - public void Information_CanDeserializeVeryLargeValues() + public void Information_CanDeserializeLargeValue() { - var original = Information.FromExabytes(1E+9); + var original = new Information(decimal.MaxValue, InformationUnit.Exbibyte); var json = SerializeObject(original); var deserialized = DeserializeObject(json); @@ -20,9 +22,10 @@ public void Information_CanDeserializeVeryLargeValues() } [Fact] - public void Information_CanDeserializeMaxValue() + public void Information_CanDeserializeSmallValue() { - var original = Information.MaxValue; + decimal decimalEpsilon = (decimal)(1 / Math.Pow(10, 28)); + var original = new Information(decimalEpsilon, InformationUnit.Bit); var json = SerializeObject(original); var deserialized = DeserializeObject(json); @@ -30,19 +33,9 @@ public void Information_CanDeserializeMaxValue() } [Fact] - public void Information_CanDeserializeMinValue() + public void Length_CanDeserializeLargeValue() { - var original = Information.MinValue; - var json = SerializeObject(original); - var deserialized = DeserializeObject(json); - - Assert.Equal(original, deserialized); - } - - [Fact] - public void Length_CanDeserializeMaxValue() - { - var original = Length.MaxValue; + var original = new Length(double.MaxValue, LengthUnit.MegalightYear); var json = SerializeObject(original); var deserialized = DeserializeObject(json); @@ -50,9 +43,9 @@ public void Length_CanDeserializeMaxValue() } [Fact] - public void Length_CanDeserializeMinValue() + public void Length_CanDeserializeSmallValue() { - var original = Length.MinValue; + var original = new Length(double.Epsilon, LengthUnit.Nanometer); var json = SerializeObject(original); var deserialized = DeserializeObject(json); diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonSerializationTests.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonSerializationTests.cs index ecad2cf236..8d8d6b2e35 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonSerializationTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonSerializationTests.cs @@ -155,7 +155,7 @@ public void MultiDimArrayValue_ExpectJsonArray() [Fact] public void EmptyArrayValue_ExpectJsonArray() { - Frequency[] testObj = new Frequency[0]; + Frequency[] testObj = { }; string expectedJson = "[]"; diff --git a/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs b/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs index 8f53ddf9d2..2b89bee8df 100644 --- a/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs +++ b/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs @@ -24,10 +24,10 @@ public class AbbreviatedUnitsConverter : JsonConverter { private const string ValueProperty = "Value"; private const string UnitProperty = "Unit"; - private const string TypeProperty = "Type"; + private const string TypeProperty = "Type"; private readonly UnitAbbreviationsCache _abbreviations; - private readonly IEqualityComparer _propertyComparer; + private readonly IEqualityComparer _propertyComparer; private readonly IDictionary _quantities; private readonly UnitParser _unitParser; @@ -43,7 +43,7 @@ public AbbreviatedUnitsConverter() /// Construct a converter using the default list of quantities and unit abbreviation provider /// /// The comparer used to compare the property/quantity names (e.g. StringComparer.OrdinalIgnoreCase) - public AbbreviatedUnitsConverter(IEqualityComparer comparer) + public AbbreviatedUnitsConverter(IEqualityComparer comparer) : this(new Dictionary(Quantity.ByName, comparer), UnitAbbreviationsCache.Default, comparer) { } @@ -54,7 +54,7 @@ public AbbreviatedUnitsConverter(IEqualityComparer comparer) /// The dictionary of quantity names /// The unit abbreviations used for the serialization /// The comparer used to compare the property names (e.g. StringComparer.OrdinalIgnoreCase) - public AbbreviatedUnitsConverter(IDictionary quantities, UnitAbbreviationsCache abbreviations, IEqualityComparer propertyComparer) + public AbbreviatedUnitsConverter(IDictionary quantities, UnitAbbreviationsCache abbreviations, IEqualityComparer propertyComparer) { _quantities = quantities; _abbreviations = abbreviations; @@ -63,7 +63,7 @@ public AbbreviatedUnitsConverter(IDictionary quantities, U } /// - public override void WriteJson(JsonWriter writer, IQuantity quantity, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, IQuantity? quantity, JsonSerializer serializer) { if (quantity is null) { @@ -85,7 +85,7 @@ public override void WriteJson(JsonWriter writer, IQuantity quantity, JsonSerial } else { - writer.WriteValue(quantity.Value); + writer.WriteValue((double)quantity.Value); } // write the 'Unit' abbreviation @@ -110,17 +110,16 @@ protected string GetQuantityType(IQuantity quantity) } /// - public override IQuantity ReadJson(JsonReader reader, Type objectType, IQuantity existingValue, bool hasExistingValue, JsonSerializer serializer) + public override IQuantity? ReadJson(JsonReader reader, Type objectType, IQuantity? existingValue, bool hasExistingValue, JsonSerializer serializer) { - QuantityInfo quantityInfo; + QuantityInfo? quantityInfo; if (reader.TokenType == JsonToken.Null) { - // return null; return TryGetQuantity(objectType.Name, out quantityInfo) ? quantityInfo.Zero : default; } - string valueToken = null; - string unitAbbreviation = null, quantityName = null; + string? valueToken = null; + string? unitAbbreviation = null, quantityName = null; if (reader.TokenType == JsonToken.StartObject) { while (reader.Read() && reader.TokenType != JsonToken.EndObject) @@ -148,6 +147,7 @@ public override IQuantity ReadJson(JsonReader reader, Type objectType, IQuantity } } + Enum unit; if (quantityName is null) { @@ -155,11 +155,15 @@ public override IQuantity ReadJson(JsonReader reader, Type objectType, IQuantity { unit = GetUnitOrDefault(unitAbbreviation, quantityInfo); } - else // the objectType doesn't match any concrete quantity type (likely it is an IQuantity) + else if (unitAbbreviation != null) // the objectType doesn't match any concrete quantity type (likely it is an IQuantity) { // failing back to an exhaustive search (it is possible that this converter was created with a short-list of non-ambiguous quantities unit = FindUnit(unitAbbreviation, out quantityInfo); } + else + { + throw new FormatException("No unit abbreviation found in JSON."); + } } else { @@ -183,7 +187,7 @@ public override IQuantity ReadJson(JsonReader reader, Type objectType, IQuantity return Quantity.From(value, unit); } - + /// /// Attempt to find an a unique (non-ambiguous) unit matching the provided abbreviation. /// @@ -203,8 +207,8 @@ protected virtual Enum FindUnit(string unitAbbreviation, out QuantityInfo quanti throw new UnitNotFoundException("The unit abbreviation and quantity type cannot both be null"); } - Enum unit = null; - quantityInfo = default; + Enum? unit = null; + QuantityInfo? tempQuantityInfo = default; foreach (var targetQuantity in _quantities.Values) { if (!TryParse(unitAbbreviation, targetQuantity, out var unitMatched)) @@ -213,20 +217,21 @@ protected virtual Enum FindUnit(string unitAbbreviation, out QuantityInfo quanti } if (unit != null && - !(targetQuantity == quantityInfo && Equals(unit, unitMatched))) // it is possible to have "synonyms": e.g. "Mass" and "Weight" + !(targetQuantity == tempQuantityInfo && Equals(unit, unitMatched))) // it is possible to have "synonyms": e.g. "Mass" and "Weight" { throw new AmbiguousUnitParseException($"Multiple quantities found matching the provided abbreviation: {unit}, {unitMatched}"); } - quantityInfo = targetQuantity; + tempQuantityInfo = targetQuantity; unit = unitMatched; } - if (unit is null) + if (unit is null || tempQuantityInfo is null) { throw new UnitNotFoundException($"No quantity found with abbreviation [{unitAbbreviation}]."); } + quantityInfo = tempQuantityInfo; return unit; } @@ -254,7 +259,7 @@ protected string GetUnitAbbreviation(Enum unit) /// Unit enum value, such as . /// No units match the abbreviation. /// More than one unit matches the abbreviation. - protected virtual Enum GetUnitOrDefault(string unitAbbreviation, QuantityInfo quantityInfo) + protected virtual Enum GetUnitOrDefault(string? unitAbbreviation, QuantityInfo quantityInfo) { return unitAbbreviation == null ? quantityInfo.BaseUnitInfo.Value @@ -269,7 +274,7 @@ protected virtual Enum GetUnitOrDefault(string unitAbbreviation, QuantityInfo qu /// Unit enum value, such as . /// No units match the abbreviation. /// More than one unit matches the abbreviation. - protected Enum Parse(string unitAbbreviation, QuantityInfo quantityInfo) + protected Enum Parse(string? unitAbbreviation, QuantityInfo quantityInfo) { return _unitParser.Parse(unitAbbreviation, quantityInfo.UnitType, CultureInfo.InvariantCulture); } @@ -283,7 +288,7 @@ protected Enum Parse(string unitAbbreviation, QuantityInfo quantityInfo) /// True if successful. /// No units match the abbreviation. /// More than one unit matches the abbreviation. - protected bool TryParse(string unitAbbreviation, QuantityInfo quantityInfo, out Enum unit) + protected bool TryParse(string? unitAbbreviation, QuantityInfo quantityInfo, out Enum? unit) { return _unitParser.TryParse(unitAbbreviation, quantityInfo.UnitType, CultureInfo.InvariantCulture, out unit); } diff --git a/UnitsNet.Serialization.JsonNet/Internal/MultiDimensionalArrayHelpers.cs b/UnitsNet.Serialization.JsonNet/Internal/MultiDimensionalArrayHelpers.cs deleted file mode 100644 index 5a675067c7..0000000000 --- a/UnitsNet.Serialization.JsonNet/Internal/MultiDimensionalArrayHelpers.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace UnitsNet.Serialization.JsonNet.Internal -{ - - /// - /// Helper class for working with and manipulating multi-dimension arrays based on their generic index. - /// - internal static class MultiDimensionalArrayHelpers - { - - /// - /// Returns a new array of same Rank and Length as but with each element converted to - /// - /// - /// - /// - public static Array ConvertArrayElements(Array array) - { - var ret = Array.CreateInstance(typeof(TResult), LastIndex(array)); - var ind = FirstIndex(array); - - while (ind != null) - { - ret.SetValue((TResult)array.GetValue(ind), ind); - ind = NextIndex(array, ind); - } - return ret; - } - - /// - /// Returns the index for the 'first' element in a multidimensional array. - /// - /// 'First' is defined as the for each rank of the - /// - /// E.g., for a zero-based 5x5x5 array this method would return [0, 0, 0]. - /// - /// - /// 1D integer array specifying the location of the first element in the multidimensional array - public static int[] FirstIndex(Array array) - { - return Enumerable.Range(0, array.Rank).Select(x => array.GetLowerBound(x)).ToArray(); - } - - /// - /// Returns the index for the 'last' element in a multidimensional array. - /// - /// 'Last' is defined as the for each rank of the - /// - /// E.g., for a zero-based 5x5x5 array this method would return [4, 4, 4]. - /// - /// - /// 1D integer array specifying the location of the last element in the multidimensional array - public static int[] LastIndex(Array array) - { - return Enumerable.Range(0, array.Rank).Select(x => array.GetUpperBound(x) + 1).ToArray(); - } - - /// - /// Returns the 'next' index after the specified multidimensional - /// - /// The 'next' index is determined by first looping through all elements in the first dimension of the array, then moving on to the next dimension and repeating - /// - /// - /// - /// Returns the index location of the next element in after as a 1D array of integers. If there is no next index, returns null - public static int[] NextIndex(Array array, int[] index) - { - for (var i = 0; i < index.Length; i++) - { - index[i] += 1; - - if (index[i] <= array.GetUpperBound(i)) - { - return index; - } - else - { - index[i] = array.GetLowerBound(i); - } - } - return null; - } - - } -} diff --git a/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs b/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs deleted file mode 100644 index c38435e291..0000000000 --- a/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace UnitsNet.Serialization.JsonNet.Internal -{ - /// - /// Helper for dealing with reflection, abstracting API differences between old and new .NET framework. - /// - [Obsolete("The JsonConverter(s) for UnitsNet no longer relies on reflection")] - internal static class ReflectionHelper - { - [Obsolete("The JsonConverter(s) for UnitsNet no longer relies on reflection")] - internal static PropertyInfo GetProperty(this Type type, string name) - { -#if (NET40 || NET35 || NET20 || SILVERLIGHT) - return type.GetProperty(name); - -#else - return type.GetTypeInfo().GetDeclaredProperty(name); -#endif - } - - [Obsolete("The JsonConverter(s) for UnitsNet no longer relies on reflection")] - internal static IEnumerable GetDeclaredMethods(this Type someType) - { - Type t = someType; - while (t != null) - { -#if (NET40 || NET35 || NET20 || SILVERLIGHT) - foreach (var m in t.GetMethods()) - yield return m; - t = t.BaseType; -#else - TypeInfo ti = t.GetTypeInfo(); - foreach (MethodInfo m in ti.DeclaredMethods) - yield return m; - t = ti.BaseType; -#endif - } - } - } -} diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj index add478c9aa..8af7ef772f 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj @@ -2,7 +2,7 @@ UnitsNet.Serialization.JsonNet - 4.6.0 + 5.0.0-alpha004 Andreas Gullberg Larsen Units.NET Serialization with Json.NET A helper library for serializing and deserializing types in Units.NET using Json.NET. @@ -20,10 +20,11 @@ - 4.0.0.0 + 5.0.0.0 latest + enable UnitsNet.Serialization.JsonNet - netstandard2.0;net40 + netstandard2.0 diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs index f73416c2ea..3373b27b26 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs @@ -5,7 +5,6 @@ using System.Collections.Concurrent; using System.Globalization; using System.Linq; -using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -18,7 +17,7 @@ namespace UnitsNet.Serialization.JsonNet /// The type being converted. Should either be or public abstract class UnitsNetBaseJsonConverter : JsonConverter { - private ConcurrentDictionary _registeredTypes = new(); + private readonly ConcurrentDictionary _registeredTypes = new(); /// /// Register custom types so that the converter can instantiate these quantities. @@ -46,7 +45,7 @@ public void RegisterCustomType(Type quantity, Type unit) /// /// The JSON data to read from /// A - protected ValueUnit ReadValueUnit(JToken jsonToken) + protected ValueUnit? ReadValueUnit(JToken jsonToken) { if (!jsonToken.HasValues) { @@ -72,7 +71,10 @@ protected ValueUnit ReadValueUnit(JToken jsonToken) return null; } - return new ValueUnit {Unit = unit.Value(), Value = value.Value()}; + return new ValueUnit { + Unit = unit.Value() ?? throw new InvalidOperationException("Unit was not a string."), + Value = value.Value() + }; } if (valueType.Type != JTokenType.String) @@ -82,7 +84,7 @@ protected ValueUnit ReadValueUnit(JToken jsonToken) return new ExtendedValueUnit { - Unit = unit.Value(), + Unit = unit.Value() ?? throw new InvalidOperationException("Unit was not a string."), Value = value.Value(), ValueType = valueType.Value(), ValueString = valueString?.Value() @@ -97,9 +99,9 @@ protected ValueUnit ReadValueUnit(JToken jsonToken) /// An IQuantity protected IQuantity ConvertValueUnit(ValueUnit valueUnit) { - if (string.IsNullOrWhiteSpace(valueUnit?.Unit)) + if (string.IsNullOrWhiteSpace(valueUnit.Unit)) { - return null; + throw new NotSupportedException("Unit must be specified."); } var unit = GetUnit(valueUnit.Unit); @@ -112,14 +114,14 @@ protected IQuantity ConvertValueUnit(ValueUnit valueUnit) return valueUnit switch { - ExtendedValueUnit {ValueType: "decimal"} extendedValueUnit => Quantity.From(decimal.Parse(extendedValueUnit.ValueString, CultureInfo.InvariantCulture), unit), + ExtendedValueUnit {ValueType: "decimal", ValueString: {}} extendedValueUnit => Quantity.From(decimal.Parse(extendedValueUnit.ValueString, CultureInfo.InvariantCulture), unit), _ => Quantity.From(valueUnit.Value, unit) }; } - private (Type Quantity, Type Unit) GetRegisteredType(string unit) + private (Type? Quantity, Type? Unit) GetRegisteredType(string unit) { - (var unitEnumTypeName, var _) = SplitUnitString(unit); + var (unitEnumTypeName, _) = SplitUnitString(unit); if (_registeredTypes.TryGetValue(unitEnumTypeName, out var registeredType)) { return registeredType; @@ -130,7 +132,7 @@ protected IQuantity ConvertValueUnit(ValueUnit valueUnit) private Enum GetUnit(string unit) { - (var unitEnumTypeName, var unitEnumValue) = SplitUnitString(unit); + var (unitEnumTypeName, unitEnumValue) = SplitUnitString(unit); // First try to find the name in the list of registered types. var unitEnumType = GetRegisteredType(unit).Unit; @@ -150,7 +152,7 @@ private Enum GetUnit(string unit) throw ex; } } - + var unitValue = (Enum) Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram return unitValue; } @@ -184,13 +186,14 @@ protected ValueUnit ConvertIQuantity(IQuantity quantity) return new ExtendedValueUnit { Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}", - Value = quantity.Value, + // The type of "Value" is still double + Value = (double)quantity.Value, ValueString = d.Value.ToString(CultureInfo.InvariantCulture), ValueType = "decimal" }; } - return new ValueUnit {Value = quantity.Value, Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}"}; + return new ValueUnit {Value = (double)quantity.Value, Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}"}; } /// @@ -251,13 +254,13 @@ protected class ValueUnit /// MassUnit.Pound /// InformationUnit.Kilobyte [JsonProperty(Order = 1)] - public string Unit { get; [UsedImplicitly] set; } + public string Unit { get; set; } = null!; /// /// The value. /// [JsonProperty(Order = 2)] - public double Value { get; [UsedImplicitly] set; } + public double Value { get; set; } } /// @@ -273,13 +276,13 @@ protected sealed class ExtendedValueUnit : ValueUnit /// The value as a string. /// [JsonProperty(Order = 3)] - public string ValueString { get; [UsedImplicitly] set; } + public string? ValueString { get; set; } /// /// The type of the value, e.g. "decimal". /// [JsonProperty(Order = 4)] - public string ValueType { get; [UsedImplicitly] set; } + public string? ValueType { get; set; } } } } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs index 66a3b57415..1e9cc3c174 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -16,7 +15,7 @@ namespace UnitsNet.Serialization.JsonNet /// Should only be used when UnitsNet types are assigned to properties of type IComparable. /// Requires TypeNameHandling on to be set to something other than so that it outputs $type when serializing. /// - public sealed class UnitsNetIComparableJsonConverter : UnitsNetBaseJsonConverter + public sealed class UnitsNetIComparableJsonConverter : UnitsNetBaseJsonConverter { /// /// Indicates if this JsonConverter is capable of writing JSON @@ -34,7 +33,7 @@ public sealed class UnitsNetIComparableJsonConverter : UnitsNetBaseJsonConverter /// Because this converter should only be used in combination with the , the WriteJson method of that converter will always be used /// to serialize an IComparable in the context of UnitsNet. /// JsonNet is capable of serializing any IComparable implementation. - public override void WriteJson(JsonWriter writer, IComparable value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, IComparable? value, JsonSerializer serializer) { throw new NotImplementedException("Serialization of IComparable is handled by default serialization"); } @@ -48,15 +47,15 @@ public override void WriteJson(JsonWriter writer, IComparable value, JsonSeriali /// Indicates if there is an existing value that should be updated (which is ignored) /// The JsonSerializer to use for deserialization /// A deserialized IComparable - public override IComparable ReadJson([NotNull] JsonReader reader, Type objectType, IComparable existingValue, bool hasExistingValue, - [NotNull] JsonSerializer serializer) + public override IComparable? ReadJson(JsonReader reader, Type objectType, IComparable? existingValue, bool hasExistingValue, + JsonSerializer serializer) { reader = reader ?? throw new ArgumentNullException(nameof(reader)); serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); if (reader.TokenType == JsonToken.Null) { - return null; + return existingValue; } var localSerializer = CreateLocalSerializer(serializer, this); @@ -66,7 +65,7 @@ public override IComparable ReadJson([NotNull] JsonReader reader, Type objectTyp // If objectType is not IComparable but a type that implements IComparable, deserialize directly as this type instead. if (objectType != typeof(IComparable)) { - return token.ToObject(objectType, localSerializer) as IComparable; + return (IComparable)token.ToObject(objectType, localSerializer)!; } var valueUnit = ReadValueUnit(token); @@ -76,7 +75,7 @@ public override IComparable ReadJson([NotNull] JsonReader reader, Type objectTyp return token.ToObject(localSerializer); } - return ConvertValueUnit(valueUnit) as IComparable; + return (IComparable)ConvertValueUnit(valueUnit); } } } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs index 4f258040f3..a7ca91baac 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -13,7 +12,7 @@ namespace UnitsNet.Serialization.JsonNet /// JSON.net converter for IQuantity types (e.g. all units in UnitsNet) /// Use this converter to serialize and deserialize UnitsNet types to and from JSON /// - public sealed class UnitsNetIQuantityJsonConverter : UnitsNetBaseJsonConverter + public sealed class UnitsNetIQuantityJsonConverter : UnitsNetBaseJsonConverter { /// /// Writes the JSON representation of the object. @@ -21,7 +20,7 @@ public sealed class UnitsNetIQuantityJsonConverter : UnitsNetBaseJsonConverterThe to write to. /// The value to write. /// The calling serializer. - public override void WriteJson([NotNull] JsonWriter writer, IQuantity value, [NotNull] JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, IQuantity? value, JsonSerializer serializer) { writer = writer ?? throw new ArgumentNullException(nameof(writer)); serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); @@ -49,21 +48,26 @@ public override void WriteJson([NotNull] JsonWriter writer, IQuantity value, [No /// The object value. /// /// Unable to parse value and unit from JSON. - public override IQuantity ReadJson([NotNull] JsonReader reader, Type objectType, IQuantity existingValue, bool hasExistingValue, - [NotNull] JsonSerializer serializer) + public override IQuantity? ReadJson(JsonReader reader, Type objectType, IQuantity? existingValue, bool hasExistingValue, + JsonSerializer serializer) { reader = reader ?? throw new ArgumentNullException(nameof(reader)); serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); if (reader.TokenType == JsonToken.Null) { - return null; + return existingValue; } var token = JToken.Load(reader); var valueUnit = ReadValueUnit(token); + if (valueUnit == null) + { + return token.ToObject(serializer); + } + return ConvertValueUnit(valueUnit); } } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs deleted file mode 100644 index 2782da5ed8..0000000000 --- a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs +++ /dev/null @@ -1,246 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using UnitsNet.Serialization.JsonNet.Internal; - -namespace UnitsNet.Serialization.JsonNet -{ - /// - /// - /// A JSON.net for converting to/from JSON and Units.NET - /// units like and . - /// - /// - /// Relies on reflection and the type names and namespaces as of 3.x.x of Units.NET. - /// Assumptions by reflection code in the converter: - /// * Unit classes are of type UnitsNet.Length etc. - /// * Unit enums are of type UnitsNet.Units.LengthUnit etc. - /// * Unit class has a BaseUnit property returning the base unit, such as LengthUnit.Meter - /// - [Obsolete("Replaced by UnitsNetIQuantityJsonConverter and UnitsNetIComparableJsonConverter (if you need support for IComparable)")] - public class UnitsNetJsonConverter : JsonConverter - { - /// - /// Reads the JSON representation of the object. - /// - /// The to read from. - /// Type of the object. - /// The existing value of object being read. - /// The calling serializer. - /// - /// The object value. - /// - /// Unable to parse value and unit from JSON. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, - JsonSerializer serializer) - { - if (reader.ValueType != null) - return reader.Value; - - object obj = TryDeserializeIComparable(reader, serializer); - if (obj is Array values) - { - - // Create array with the requested type, such as `Length[]` or `Frequency[]` or multi-dimensional arrays like `Length[,]` or `Frequency[,,]` - var arrayOfQuantities = Array.CreateInstance(objectType.GetElementType(), MultiDimensionalArrayHelpers.LastIndex(values)); - - // Fill array with parsed quantities - int[] index = MultiDimensionalArrayHelpers.FirstIndex(values); - while (index != null) - { - arrayOfQuantities.SetValue(values.GetValue(index), index); - } - - return arrayOfQuantities; - } - else if (obj is ValueUnit valueUnit) - { - return ParseValueUnit(valueUnit); - } - else - { - return obj; - } - } - - private static IQuantity ParseValueUnit(ValueUnit vu) - { - // "MassUnit.Kilogram" => "MassUnit" and "Kilogram" - string unitEnumTypeName = vu.Unit.Split('.')[0]; - string unitEnumValue = vu.Unit.Split('.')[1]; - - // "UnitsNet.Units.MassUnit,UnitsNet" - string unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; - - // -- see http://stackoverflow.com/a/6465096/1256096 for details - Type unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); - if (unitEnumType == null) - { - var ex = new UnitsNetException("Unable to find enum type."); - ex.Data["type"] = unitEnumTypeAssemblyQualifiedName; - throw ex; - } - - double value = vu.Value; - Enum unitValue = (Enum)Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram - - return Quantity.From(value, unitValue); - } - - private static object TryDeserializeIComparable(JsonReader reader, JsonSerializer serializer) - { - JToken token = JToken.Load(reader); - - if (token is JArray) - { - object[] results = token.Children().Select(item => TryDeserializeIComparable(item, serializer)).ToArray(); - return results; - } - else - { - return TryDeserializeIComparable(token, serializer); - } - } - - private static object TryDeserializeIComparable(JToken token, JsonSerializer serializer) - { - if (!token.HasValues || token[nameof(ValueUnit.Unit)] == null || token[nameof(ValueUnit.Value)] == null) - { - var localSerializer = new JsonSerializer - { - TypeNameHandling = serializer.TypeNameHandling, - }; - return token.ToObject(localSerializer); - } - else - { - return new ValueUnit - { - Unit = token[nameof(ValueUnit.Unit)].ToString(), - Value = token[nameof(ValueUnit.Value)].ToObject() - }; - } - } - - /// - /// Writes the JSON representation of the object. - /// - /// The to write to. - /// The value to write. - /// The calling serializer. - /// Can't serialize 'null' value. - public override void WriteJson(JsonWriter writer, object obj, JsonSerializer serializer) - { - // ValueUnit should be written as usual (but read in a custom way) - if (obj is ValueUnit valueUnit) - { - var localSerializer = new JsonSerializer - { - TypeNameHandling = serializer.TypeNameHandling, - }; - - var t = JToken.FromObject(valueUnit, localSerializer); - t.WriteTo(writer); - } - else if (obj is Array values) - { - - var results = Array.CreateInstance(typeof(ValueUnit), MultiDimensionalArrayHelpers.LastIndex(values)); - var ind = MultiDimensionalArrayHelpers.FirstIndex(values); - - while (ind != null) - { - results.SetValue((IQuantity)values.GetValue(ind), ind); - ind = MultiDimensionalArrayHelpers.NextIndex(results, ind); - } - - serializer.Serialize(writer, results); - } - else if (obj is IQuantity quantity) - { - serializer.Serialize(writer, ToValueUnit(quantity)); - } - else - { - throw new NotSupportedException($"Unsupported type: {obj.GetType()}"); - } - } - - private static ValueUnit ToValueUnit(IQuantity value) - { - return new ValueUnit - { - // See ValueUnit about precision loss for quantities using decimal type. - Value = value.Value, - Unit = $"{value.QuantityInfo.UnitType.Name}.{value.Unit}" - }; - } - - /// - /// A structure used to serialize/deserialize Units.NET unit instances. - /// - /// - /// Quantities may use decimal, long or double as base value type and this might result - /// in a loss of precision when serializing/deserializing to decimal. - /// Decimal is the highest precision type available in .NET, but has a smaller - /// range than double. - /// - /// Json: Support decimal precision #503 - /// https://github.com/angularsen/UnitsNet/issues/503 - /// - private class ValueUnit - { - public string Unit { get; [UsedImplicitly] set; } - public double Value { get; [UsedImplicitly] set; } - } - - #region Can Convert - - /// - /// Determines whether this instance can convert the specified object type. - /// - /// Type of the object. - /// - public override bool CanConvert(Type objectType) - { - if (IsNullable(objectType)) - return CanConvertNullable(objectType); - - return objectType.Namespace != null && - (objectType.Namespace.Equals(nameof(UnitsNet)) || - objectType == typeof(ValueUnit) || - // All unit types implement IComparable - objectType == typeof(IComparable)); - } - - /// - /// Determines whether the specified object type is actually a type. - /// - /// Type of the object. - /// true if the object type is nullable; otherwise false. - private static bool IsNullable(Type objectType) - { - return Nullable.GetUnderlyingType(objectType) != null; - } - - /// - /// Determines whether this instance can convert the specified nullable object type. - /// - /// Type of the object. - /// true if the object type is a nullable container for a UnitsNet type; otherwise false. - protected virtual bool CanConvertNullable(Type objectType) - { - // Need to look at the FullName in order to determine if the nullable type contains a UnitsNet type. - // For example: FullName = 'System.Nullable`1[[UnitsNet.Frequency, UnitsNet, Version=3.19.0.0, Culture=neutral, PublicKeyToken=null]]' - return objectType.FullName != null && objectType.FullName.Contains(nameof(UnitsNet) + "."); - } - - #endregion - - } -} diff --git a/UnitsNet.Tests/AssertEx.cs b/UnitsNet.Tests/AssertEx.cs index d052adfeec..229e4324e7 100644 --- a/UnitsNet.Tests/AssertEx.cs +++ b/UnitsNet.Tests/AssertEx.cs @@ -25,5 +25,23 @@ public static void EqualTolerance(double expected, double actual, double toleran Assert.True( areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}" ); } } + + public static void EqualTolerance(decimal expected, decimal actual, decimal tolerance, ComparisonType comparisonType = ComparisonType.Relative) + { + if (comparisonType == ComparisonType.Relative) + { + bool areEqual = Comparison.EqualsRelative(expected, actual, tolerance); + + decimal difference = Math.Abs(expected - actual); + decimal relativeDifference = difference / expected; + + Assert.True(areEqual, $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}"); + } + else if (comparisonType == ComparisonType.Absolute) + { + bool areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); + Assert.True(areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}"); + } + } } } diff --git a/UnitsNet.Tests/BaseUnitsTests.cs b/UnitsNet.Tests/BaseUnitsTests.cs index 3954e61b93..545448e2ac 100644 --- a/UnitsNet.Tests/BaseUnitsTests.cs +++ b/UnitsNet.Tests/BaseUnitsTests.cs @@ -9,13 +9,13 @@ namespace UnitsNet.Tests { public class BaseUnitsTests { - private static BaseUnits siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + private static readonly BaseUnits SIBaseUnits = new(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - private static BaseUnits siBaseUnitsCopy = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + private static readonly BaseUnits SIBaseUnitsCopy = new(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - private static BaseUnits nonSiBaseUnits = new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + private static readonly BaseUnits NonSiBaseUnits = new(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); [Fact] @@ -36,36 +36,36 @@ public void ConstructorSetsUnitsProperly() [Fact] public void EqualsObjectIsImplementedCorrectly() { - Assert.True(siBaseUnits.Equals((object)siBaseUnitsCopy)); - Assert.False(siBaseUnits.Equals((object)nonSiBaseUnits)); + Assert.True(SIBaseUnits.Equals((object)SIBaseUnitsCopy)); + Assert.False(SIBaseUnits.Equals((object)NonSiBaseUnits)); - Assert.False(siBaseUnits.Equals("Some object.")); - Assert.False(siBaseUnits.Equals((IFormatProvider)null)); + Assert.False(SIBaseUnits.Equals("Some object.")); + Assert.False(SIBaseUnits.Equals(((IFormatProvider)null)!)); } [Fact] public void EqualsBaseUnitsIsImplementedCorrectly() { - Assert.True(siBaseUnits.Equals(siBaseUnitsCopy)); - Assert.True(siBaseUnitsCopy.Equals(siBaseUnits)); + Assert.True(SIBaseUnits.Equals(SIBaseUnitsCopy)); + Assert.True(SIBaseUnitsCopy.Equals(SIBaseUnits)); - Assert.False(siBaseUnits.Equals(nonSiBaseUnits)); - Assert.False(nonSiBaseUnits.Equals(siBaseUnits)); + Assert.False(SIBaseUnits.Equals(NonSiBaseUnits)); + Assert.False(NonSiBaseUnits.Equals(SIBaseUnits)); - Assert.False(siBaseUnits.Equals(null)); + Assert.False(SIBaseUnits.Equals(null!)); } [Fact] public void EqualityOperatorIsImplementedCorrectly() { - Assert.True(siBaseUnits == siBaseUnitsCopy); - Assert.True(siBaseUnitsCopy == siBaseUnits); + Assert.True(SIBaseUnits == SIBaseUnitsCopy); + Assert.True(SIBaseUnitsCopy == SIBaseUnits); - Assert.False(siBaseUnits == nonSiBaseUnits); - Assert.False(nonSiBaseUnits == siBaseUnits); + Assert.False(SIBaseUnits == NonSiBaseUnits); + Assert.False(NonSiBaseUnits == SIBaseUnits); - Assert.False(siBaseUnits == null); - Assert.False(null == siBaseUnits); + Assert.False(SIBaseUnits == null); + Assert.False(null == SIBaseUnits); BaseUnits nullBaseUnits1 = null; BaseUnits nullBaseUnits2 = null; @@ -76,14 +76,14 @@ public void EqualityOperatorIsImplementedCorrectly() [Fact] public void InequalityOperatorIsImplementedCorrectly() { - Assert.False(siBaseUnits != siBaseUnitsCopy); - Assert.False(siBaseUnitsCopy != siBaseUnits); + Assert.False(SIBaseUnits != SIBaseUnitsCopy); + Assert.False(SIBaseUnitsCopy != SIBaseUnits); - Assert.True(siBaseUnits != nonSiBaseUnits); - Assert.True(nonSiBaseUnits != siBaseUnits); + Assert.True(SIBaseUnits != NonSiBaseUnits); + Assert.True(NonSiBaseUnits != SIBaseUnits); - Assert.True(siBaseUnits != null); - Assert.True(null != siBaseUnits); + Assert.True(SIBaseUnits != null); + Assert.True(null != SIBaseUnits); BaseUnits nullBaseUnits1 = null; BaseUnits nullBaseUnits2 = null; @@ -94,13 +94,13 @@ public void InequalityOperatorIsImplementedCorrectly() [Fact] public void UndefinedHasAllBaseUnitsAsUndefined() { - Assert.Equal(LengthUnit.Undefined, BaseUnits.Undefined.Length); - Assert.Equal(MassUnit.Undefined, BaseUnits.Undefined.Mass); - Assert.Equal(DurationUnit.Undefined, BaseUnits.Undefined.Time); - Assert.Equal(ElectricCurrentUnit.Undefined, BaseUnits.Undefined.Current); - Assert.Equal(TemperatureUnit.Undefined, BaseUnits.Undefined.Temperature); - Assert.Equal(AmountOfSubstanceUnit.Undefined, BaseUnits.Undefined.Amount); - Assert.Equal(LuminousIntensityUnit.Undefined, BaseUnits.Undefined.LuminousIntensity); + Assert.Null(BaseUnits.Undefined.Length); + Assert.Null(BaseUnits.Undefined.Mass); + Assert.Null(BaseUnits.Undefined.Time); + Assert.Null(BaseUnits.Undefined.Current); + Assert.Null(BaseUnits.Undefined.Temperature); + Assert.Null(BaseUnits.Undefined.Amount); + Assert.Null(BaseUnits.Undefined.LuminousIntensity); } [Fact] @@ -112,20 +112,20 @@ public void UndefinedIsSubsetOfUndefined() [Fact] public void IsSubsetOfReturnsFalseWithNull() { - Assert.False(siBaseUnits.IsSubsetOf(null)); + Assert.Throws(() => SIBaseUnits.IsSubsetOf(null!)); } [Fact] public void ExistsInWorksCorrectly() { - Assert.False(BaseUnits.Undefined.IsSubsetOf(siBaseUnits)); - Assert.False(siBaseUnits.IsSubsetOf(BaseUnits.Undefined)); + Assert.False(BaseUnits.Undefined.IsSubsetOf(SIBaseUnits)); + Assert.False(SIBaseUnits.IsSubsetOf(BaseUnits.Undefined)); var meterBaseUnits = new BaseUnits(LengthUnit.Meter); - Assert.True(meterBaseUnits.IsSubsetOf(siBaseUnits)); + Assert.True(meterBaseUnits.IsSubsetOf(SIBaseUnits)); // Not all units in siBaseUnits will exist in meterBaseUnits - Assert.False(siBaseUnits.IsSubsetOf(meterBaseUnits)); + Assert.False(SIBaseUnits.IsSubsetOf(meterBaseUnits)); } [Fact] @@ -144,7 +144,7 @@ public void IsFullyDefined_TrueIfAllBaseUnitDefined() ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela).IsFullyDefined); } - + [Fact] public void IsFullyDefined_FalseIfAnyBaseUnitIsUndefined() { diff --git a/UnitsNet.Tests/CustomCode/BitRateTests.cs b/UnitsNet.Tests/CustomCode/BitRateTests.cs index 2afe11ae27..5e49dc8ad3 100644 --- a/UnitsNet.Tests/CustomCode/BitRateTests.cs +++ b/UnitsNet.Tests/CustomCode/BitRateTests.cs @@ -29,37 +29,37 @@ public class BitRateTests : BitRateTestsBase { protected override bool SupportsSIUnitSystem => false; - protected override double BitsPerSecondInOneBitPerSecond => 1d; - protected override double BytesPerSecondInOneBitPerSecond => 1.25E-1d; + protected override decimal BitsPerSecondInOneBitPerSecond => 1m; + protected override decimal BytesPerSecondInOneBitPerSecond => 1.25E-1m; - protected override double KilobitsPerSecondInOneBitPerSecond => 1E-3d; - protected override double KilobytesPerSecondInOneBitPerSecond => 1.25E-4d; - protected override double KibibitsPerSecondInOneBitPerSecond => 0.0009765625d; - protected override double KibibytesPerSecondInOneBitPerSecond => 0.0001220703125d; + protected override decimal KilobitsPerSecondInOneBitPerSecond => 1E-3m; + protected override decimal KilobytesPerSecondInOneBitPerSecond => 1.25E-4m; + protected override decimal KibibitsPerSecondInOneBitPerSecond => 0.0009765625m; + protected override decimal KibibytesPerSecondInOneBitPerSecond => 0.0001220703125m; - protected override double MegabitsPerSecondInOneBitPerSecond => 1E-6d; - protected override double MegabytesPerSecondInOneBitPerSecond => 1.25E-07d; - protected override double MebibitsPerSecondInOneBitPerSecond => 9.5367431640625E-07d; - protected override double MebibytesPerSecondInOneBitPerSecond => 1.19209289550781E-07d; + protected override decimal MegabitsPerSecondInOneBitPerSecond => 1E-6m; + protected override decimal MegabytesPerSecondInOneBitPerSecond => 1.25E-07m; + protected override decimal MebibitsPerSecondInOneBitPerSecond => 9.5367431640625E-07m; + protected override decimal MebibytesPerSecondInOneBitPerSecond => 1.19209289550781E-07m; - protected override double GigabitsPerSecondInOneBitPerSecond => 1E-9d; - protected override double GigabytesPerSecondInOneBitPerSecond => 1.25E-10d; - protected override double GibibitsPerSecondInOneBitPerSecond => 9.31322574615479E-10d; - protected override double GibibytesPerSecondInOneBitPerSecond => 1.16415321826935E-10d; + protected override decimal GigabitsPerSecondInOneBitPerSecond => 1E-9m; + protected override decimal GigabytesPerSecondInOneBitPerSecond => 1.25E-10m; + protected override decimal GibibitsPerSecondInOneBitPerSecond => 9.31322574615479E-10m; + protected override decimal GibibytesPerSecondInOneBitPerSecond => 1.16415321826935E-10m; - protected override double TerabitsPerSecondInOneBitPerSecond => 1E-12d; - protected override double TerabytesPerSecondInOneBitPerSecond => 1.25E-13d; - protected override double TebibitsPerSecondInOneBitPerSecond => 9.09494701772928E-13d; - protected override double TebibytesPerSecondInOneBitPerSecond => 1.13686837721616E-13d; + protected override decimal TerabitsPerSecondInOneBitPerSecond => 1E-12m; + protected override decimal TerabytesPerSecondInOneBitPerSecond => 1.25E-13m; + protected override decimal TebibitsPerSecondInOneBitPerSecond => 9.09494701772928E-13m; + protected override decimal TebibytesPerSecondInOneBitPerSecond => 1.13686837721616E-13m; - protected override double PetabitsPerSecondInOneBitPerSecond => 1E-15d; - protected override double PetabytesPerSecondInOneBitPerSecond => 1.25E-16d; - protected override double PebibitsPerSecondInOneBitPerSecond => 8.88178419700125E-16d; - protected override double PebibytesPerSecondInOneBitPerSecond => 1.11022302462516E-16d; + protected override decimal PetabitsPerSecondInOneBitPerSecond => 1E-15m; + protected override decimal PetabytesPerSecondInOneBitPerSecond => 1.25E-16m; + protected override decimal PebibitsPerSecondInOneBitPerSecond => 8.88178419700125E-16m; + protected override decimal PebibytesPerSecondInOneBitPerSecond => 1.11022302462516E-16m; - protected override double ExabitsPerSecondInOneBitPerSecond => 1E-18d; - protected override double ExabytesPerSecondInOneBitPerSecond => 1.25E-19d; - protected override double ExbibitsPerSecondInOneBitPerSecond => 8.67361738E-19d; - protected override double ExbibytesPerSecondInOneBitPerSecond => 1.0842021724855E-19d; + protected override decimal ExabitsPerSecondInOneBitPerSecond => 1E-18m; + protected override decimal ExabytesPerSecondInOneBitPerSecond => 1.25E-19m; + protected override decimal ExbibitsPerSecondInOneBitPerSecond => 8.67361738E-19m; + protected override decimal ExbibytesPerSecondInOneBitPerSecond => 1.0842021724855E-19m; } } diff --git a/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs b/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs index d970c4fb33..de64c8bdcd 100644 --- a/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs @@ -20,7 +20,6 @@ public class ElectricResistanceTests : ElectricResistanceTestsBase protected override double GigaohmsInOneOhm => 1e-9; - [Theory] [InlineData(1, 1, 1)] [InlineData(0, int.MaxValue, 0)] diff --git a/UnitsNet.Tests/CustomCode/InformationTests.cs b/UnitsNet.Tests/CustomCode/InformationTests.cs index a65933ef4b..4e2b1fa474 100644 --- a/UnitsNet.Tests/CustomCode/InformationTests.cs +++ b/UnitsNet.Tests/CustomCode/InformationTests.cs @@ -9,75 +9,62 @@ namespace UnitsNet.Tests.CustomCode public class InformationTests : InformationTestsBase { protected override bool SupportsSIUnitSystem => false; - protected override double BitsInOneBit => 1d; + protected override decimal BitsInOneBit => 1m; - protected override double BytesInOneBit => 0.125d; + protected override decimal BytesInOneBit => 0.125m; - protected override double ExabitsInOneBit => 1e-18d; + protected override decimal ExabitsInOneBit => 1e-18m; - protected override double ExabytesInOneBit => 0.125d*1e-18d; + protected override decimal ExabytesInOneBit => 0.125m*1e-18m; - protected override double ExbibitsInOneBit => 1d/Math.Pow(1024, 6); + protected override decimal ExbibitsInOneBit => 1m/(decimal)Math.Pow(1024, 6); - protected override double ExbibytesInOneBit => 1/8d/Math.Pow(1024, 6); + protected override decimal ExbibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 6); - protected override double GibibitsInOneBit => 1d/Math.Pow(1024, 3); + protected override decimal GibibitsInOneBit => 1m/(decimal)Math.Pow(1024, 3); - protected override double GibibytesInOneBit => 1d/8/Math.Pow(1024, 3); + protected override decimal GibibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 3); - protected override double GigabitsInOneBit => 1e-9d; + protected override decimal GigabitsInOneBit => 1e-9m; - protected override double GigabytesInOneBit => 0.125d*1e-9d; + protected override decimal GigabytesInOneBit => 0.125m*1e-9m; - protected override double KibibitsInOneBit => 1d/1024d; + protected override decimal KibibitsInOneBit => 1m/1024m; - protected override double KibibytesInOneBit => 1d/8/1024d; + protected override decimal KibibytesInOneBit => 1m/8/1024m; - protected override double KilobitsInOneBit => 0.001d; + protected override decimal KilobitsInOneBit => 0.001m; - protected override double KilobytesInOneBit => 0.000125d; + protected override decimal KilobytesInOneBit => 0.000125m; - protected override double MebibitsInOneBit => 1d/Math.Pow(1024, 2); + protected override decimal MebibitsInOneBit => 1m/(decimal)Math.Pow(1024, 2); - protected override double MebibytesInOneBit => 1d/8/Math.Pow(1024, 2); + protected override decimal MebibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 2); - protected override double MegabitsInOneBit => 1e-6d; + protected override decimal MegabitsInOneBit => 1e-6m; - protected override double MegabytesInOneBit => 0.125d*1e-6d; + protected override decimal MegabytesInOneBit => 0.125m*1e-6m; - protected override double PebibitsInOneBit => 1d/Math.Pow(1024, 5); + protected override decimal PebibitsInOneBit => 1m/(decimal)Math.Pow(1024, 5); - protected override double PebibytesInOneBit => 1d/8/Math.Pow(1024, 5); + protected override decimal PebibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 5); - protected override double PetabitsInOneBit => 1e-15d; + protected override decimal PetabitsInOneBit => 1e-15m; - protected override double PetabytesInOneBit => 0.125d*1e-15d; + protected override decimal PetabytesInOneBit => 0.125m*1e-15m; - protected override double TebibitsInOneBit => 1d/Math.Pow(1024, 4); + protected override decimal TebibitsInOneBit => 1m/(decimal)Math.Pow(1024, 4); - protected override double TebibytesInOneBit => 1d/8/Math.Pow(1024, 4); + protected override decimal TebibytesInOneBit => 1m/8m/(decimal)Math.Pow(1024, 4); - protected override double TerabitsInOneBit => 1e-12d; + protected override decimal TerabitsInOneBit => 1e-12m; - protected override double TerabytesInOneBit => 0.125d*1e-12d; + protected override decimal TerabytesInOneBit => 0.125m*1e-12m; -// ReSharper disable once InconsistentNaming [Fact] public void OneKBHas1000Bytes() { Assert.Equal(1000, Information.FromKilobytes(1).Bytes); } - - [Fact] - public void MaxValueIsCorrectForUnitWithBaseTypeDecimal() - { - Assert.Equal((double) decimal.MaxValue, Information.MaxValue.Bits); - } - - [Fact] - public void MinValueIsCorrectForUnitWithBaseTypeDecimal() - { - Assert.Equal((double) decimal.MinValue, Information.MinValue.Bits); - } } } diff --git a/UnitsNet.Tests/CustomCode/LengthTests.cs b/UnitsNet.Tests/CustomCode/LengthTests.cs index 78ff80c6d4..8354c069fd 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.cs @@ -154,18 +154,6 @@ public void ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() Assert.Equal("2 cm", valueString); } - [Fact] - public void MaxValueIsCorrectForUnitWithBaseTypeDouble() - { - Assert.Equal(double.MaxValue, Length.MaxValue.Meters); - } - - [Fact] - public void MinValueIsCorrectForUnitWithBaseTypeDouble() - { - Assert.Equal(double.MinValue, Length.MinValue.Meters); - } - [Fact] public void NegativeLengthToStonePoundsReturnsCorrectValues() { diff --git a/UnitsNet.Tests/CustomCode/MassConcentrationTests.cs b/UnitsNet.Tests/CustomCode/MassConcentrationTests.cs index 187ac024bc..05dc6123f8 100644 --- a/UnitsNet.Tests/CustomCode/MassConcentrationTests.cs +++ b/UnitsNet.Tests/CustomCode/MassConcentrationTests.cs @@ -136,7 +136,6 @@ public static void ComponentMassFromMassConcentrationAndSolutionVolume( AssertEx.EqualTolerance(expectedMassValue, massComponent.As(expectedMassUnit), tolerance); } - [Fact(Skip = "No BaseUnit defined: see https://github.com/angularsen/UnitsNet/issues/651")] public void DefaultSIUnitIsKgPerCubicMeter() { diff --git a/UnitsNet.Tests/CustomCode/MassFlowTests.cs b/UnitsNet.Tests/CustomCode/MassFlowTests.cs index e59fa41f18..711f82b28d 100644 --- a/UnitsNet.Tests/CustomCode/MassFlowTests.cs +++ b/UnitsNet.Tests/CustomCode/MassFlowTests.cs @@ -76,7 +76,6 @@ public class MassFlowTests : MassFlowTestsBase protected override double GramsPerHourInOneGramPerSecond => 3600; - [Fact] public void DurationTimesMassFlowEqualsMass() { @@ -109,7 +108,7 @@ public void TimeSpanTimesMassFlowEqualsMass() public void MassFlowDividedByBrakeSpecificFuelConsumptionEqualsPower() { Power power = MassFlow.FromTonnesPerDay(20) / BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); - Assert.Equal(20.0 / 24.0 * 1e6 / 180.0, power.Kilowatts); + AssertEx.EqualTolerance(20.0m / 24.0m * 1e6m / 180.0m, power.Kilowatts, 1E-11m); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/MassFluxTests.cs b/UnitsNet.Tests/CustomCode/MassFluxTests.cs index 99be1f8e51..2fe8cea5e5 100644 --- a/UnitsNet.Tests/CustomCode/MassFluxTests.cs +++ b/UnitsNet.Tests/CustomCode/MassFluxTests.cs @@ -43,7 +43,6 @@ public class MassFluxTests : MassFluxTestsBase protected override double KilogramsPerHourPerSquareCentimeterInOneKilogramPerSecondPerSquareMeter => 3.6E-1; protected override double KilogramsPerHourPerSquareMillimeterInOneKilogramPerSecondPerSquareMeter => 3.6E-3; - [Fact] public void MassFluxDividedBySpeedEqualsDensity() { diff --git a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs index e6820ea023..7e149043e6 100644 --- a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs @@ -46,6 +46,7 @@ public void ExpectPowerConvertedCorrectly(double power, double expected) } [Theory] + // Note: Attribute arguments cannot be of type decimal. [InlineData(-20, 0.01)] [InlineData(-10, 0.1)] [InlineData(0, 1)] @@ -54,8 +55,8 @@ public void ExpectPowerConvertedCorrectly(double power, double expected) public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expected) { PowerRatio pr = PowerRatio.FromDecibelWatts(powerRatio); - double actual = pr.ToPower().Watts; - Assert.Equal(expected, actual); + decimal actual = pr.ToPower().Watts; + Assert.Equal((decimal)expected, actual); } // http://www.maximintegrated.com/en/app-notes/index.mvp/id/808 diff --git a/UnitsNet.Tests/CustomCode/PowerTests.cs b/UnitsNet.Tests/CustomCode/PowerTests.cs index b965e8fa83..8161a50849 100644 --- a/UnitsNet.Tests/CustomCode/PowerTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerTests.cs @@ -9,57 +9,57 @@ namespace UnitsNet.Tests.CustomCode public class PowerTests : PowerTestsBase { protected override bool SupportsSIUnitSystem => false; - protected override double FemtowattsInOneWatt => 1e15; + protected override decimal FemtowattsInOneWatt => 1e15m; - protected override double GigajoulesPerHourInOneWatt => 3600e-9; + protected override decimal GigajoulesPerHourInOneWatt => 3600e-9m; - protected override double PicowattsInOneWatt => 1e12; + protected override decimal PicowattsInOneWatt => 1e12m; - protected override double NanowattsInOneWatt => 1e9; + protected override decimal NanowattsInOneWatt => 1e9m; - protected override double MicrowattsInOneWatt => 1e6; + protected override decimal MicrowattsInOneWatt => 1e6m; - protected override double MillijoulesPerHourInOneWatt => 3600e3; + protected override decimal MillijoulesPerHourInOneWatt => 3600e3m; - protected override double MilliwattsInOneWatt => 1e3; + protected override decimal MilliwattsInOneWatt => 1e3m; - protected override double DeciwattsInOneWatt => 1e1; + protected override decimal DeciwattsInOneWatt => 1e1m; - protected override double WattsInOneWatt => 1; + protected override decimal WattsInOneWatt => 1; - protected override double DecawattsInOneWatt => 1e-1; + protected override decimal DecawattsInOneWatt => 1e-1m; - protected override double KilojoulesPerHourInOneWatt => 3600e-3; + protected override decimal KilojoulesPerHourInOneWatt => 3600e-3m; - protected override double KilowattsInOneWatt => 1e-3; + protected override decimal KilowattsInOneWatt => 1e-3m; - protected override double MegajoulesPerHourInOneWatt => 3600e-6; + protected override decimal MegajoulesPerHourInOneWatt => 3600e-6m; - protected override double MegawattsInOneWatt => 1e-6; + protected override decimal MegawattsInOneWatt => 1e-6m; - protected override double GigawattsInOneWatt => 1e-9; + protected override decimal GigawattsInOneWatt => 1e-9m; - protected override double TerawattsInOneWatt => 1e-12; + protected override decimal TerawattsInOneWatt => 1e-12m; - protected override double PetawattsInOneWatt => 1e-15; + protected override decimal PetawattsInOneWatt => 1e-15m; - protected override double JoulesPerHourInOneWatt => 3600; + protected override decimal JoulesPerHourInOneWatt => 3600; - protected override double KilobritishThermalUnitsPerHourInOneWatt => 3.412141633e-3; + protected override decimal KilobritishThermalUnitsPerHourInOneWatt => 3.412141633e-3m; - protected override double MegabritishThermalUnitsPerHourInOneWatt => 3.412141633e-6; + protected override decimal BoilerHorsepowerInOneWatt => 1.0191082802547770700636942675159e-4m; - protected override double BoilerHorsepowerInOneWatt => 1.0191082802547770700636942675159e-4; + protected override decimal MegabritishThermalUnitsPerHourInOneWatt => 3.412141633e-6m; - protected override double BritishThermalUnitsPerHourInOneWatt => 3.412141633; + protected override decimal BritishThermalUnitsPerHourInOneWatt => 3.412141633m; - protected override double ElectricalHorsepowerInOneWatt => 0.00134048257372654155495978552279; + protected override decimal ElectricalHorsepowerInOneWatt => 0.00134048257372654155495978552279m; - protected override double HydraulicHorsepowerInOneWatt => 0.00134102207184949258114167291719; + protected override decimal HydraulicHorsepowerInOneWatt => 0.00134102207184949258114167291719m; - protected override double MechanicalHorsepowerInOneWatt => 0.00134103984229371454625916935992; + protected override decimal MechanicalHorsepowerInOneWatt => 0.00134103984229371454625916935992m; - protected override double MetricHorsepowerInOneWatt => 0.00135962161730390432342679032425; + protected override decimal MetricHorsepowerInOneWatt => 0.00135962161730390432342679032425m; [Fact] public void DurationTimesPowerEqualsEnergy() diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index e6c3128cfa..940aa61d69 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -3,7 +3,7 @@ using System; using UnitsNet.CustomCode.Units; -using UnitsNet.CustomCode.Wrappers; +using UnitsNet.Wrappers; using Xunit; namespace UnitsNet.Tests.CustomCode @@ -217,12 +217,6 @@ public void Reference_WithDefaultPressureReference_IsAbsolute() Equals(PressureReference.Absolute, refPressure.Reference); } - [Fact] - public void ReferencesDoesNotContainUndefined() - { - Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); - } - [Fact] public void Vacuum_WithDefaultPressureReference_IsOneLessAtmosphereNegative() { diff --git a/UnitsNet.Tests/CustomCode/ReciprocalAreaTests.cs b/UnitsNet.Tests/CustomCode/ReciprocalAreaTests.cs index dcb1625f6e..f73da0cbb3 100644 --- a/UnitsNet.Tests/CustomCode/ReciprocalAreaTests.cs +++ b/UnitsNet.Tests/CustomCode/ReciprocalAreaTests.cs @@ -33,7 +33,6 @@ public class ReciprocalAreaTests : ReciprocalAreaTestsBase protected override double InverseSquareMillimetersInOneInverseSquareMeter => 1E-6; protected override double InverseSquareMicrometersInOneInverseSquareMeter => 1E-12; - protected override double InverseSquareMilesInOneInverseSquareMeter => 2.59E6; protected override double InverseSquareYardsInOneInverseSquareMeter => 0.836127; protected override double InverseSquareFeetInOneInverseSquareMeter => 0.092903; diff --git a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs index 6ff3dac8df..bf5e3530e3 100644 --- a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs @@ -45,7 +45,6 @@ public class SpecificEnergyTests : SpecificEnergyTestsBase protected override double GigawattDaysPerTonneInOneJoulePerKilogram => 1.15740741E-11; protected override double TerawattDaysPerTonneInOneJoulePerKilogram => 1.15740741E-14; - [Fact] public void MassTimesSpecificEnergyEqualsEnergy() { @@ -71,7 +70,7 @@ public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption() public void SpecificEnergyTimesMassFlowEqualsPower() { Power power = SpecificEnergy.FromJoulesPerKilogram(10.0) * MassFlow.FromKilogramsPerSecond(20.0); - Assert.Equal(200d, power.Watts); + Assert.Equal(200m, power.Watts); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/StonePoundsTests.cs b/UnitsNet.Tests/CustomCode/StonePoundsTests.cs index 76803c88d6..1191f3dc50 100644 --- a/UnitsNet.Tests/CustomCode/StonePoundsTests.cs +++ b/UnitsNet.Tests/CustomCode/StonePoundsTests.cs @@ -35,7 +35,7 @@ public void StonePoundsToString_FormatsNumberInDefaultCulture() { Mass m = Mass.FromStonePounds(3500, 1); StonePounds stonePounds = m.StonePounds; - string numberInCurrentCulture = 3500.ToString("n0", CultureInfo.CurrentUICulture); // Varies between machines, can't hard code it + string numberInCurrentCulture = 3500.ToString("n0", CultureInfo.CurrentCulture); // Varies between machines, can't hard code it Assert.Equal($"{numberInCurrentCulture} st 1 lb", stonePounds.ToString()); } diff --git a/UnitsNet.Tests/CustomCode/TemperatureTests.cs b/UnitsNet.Tests/CustomCode/TemperatureTests.cs index 441ce154ae..406ee33953 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureTests.cs @@ -121,8 +121,6 @@ public void TemperatureMinusTemperatureDeltaEqualsTemperature(Temperature temper new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } }; - - [Theory] [MemberData(nameof(TemperaturePlusTemperatureDeltaEqualsTemperatureData))] public void TemperaturePlusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index ff41feb577..908caecfa9 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -17,16 +17,15 @@ public HowMuch(double value, HowMuchUnit unit) Enum IQuantity.Unit => Unit; public HowMuchUnit Unit { get; } - public double Value { get; } + public QuantityValue Value { get; } #region IQuantity private static readonly HowMuch Zero = new HowMuch(0, HowMuchUnit.Some); - public QuantityType Type => QuantityType.Undefined; public BaseDimensions Dimensions => BaseDimensions.Dimensionless; - public QuantityInfo QuantityInfo => new QuantityInfo( + public QuantityInfo QuantityInfo => new( nameof(HowMuch), typeof(HowMuchUnit), new UnitInfo[] diff --git a/UnitsNet.Tests/DecimalOverloadTests.cs b/UnitsNet.Tests/DecimalOverloadTests.cs index 841c9b162b..6b9842d0aa 100644 --- a/UnitsNet.Tests/DecimalOverloadTests.cs +++ b/UnitsNet.Tests/DecimalOverloadTests.cs @@ -18,7 +18,7 @@ public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorre public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() { Power power = Power.FromWatts(1m); - Assert.Equal(1.0, power.Watts); + Assert.Equal(1.0m, power.Watts); } } } diff --git a/UnitsNet.Tests/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs index 6bcb848c2d..bd9f57c2e7 100644 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ b/UnitsNet.Tests/DummyIQuantity.cs @@ -1,36 +1,30 @@ -using System; -using JetBrains.Annotations; +#nullable enable +using System; namespace UnitsNet.Tests { internal class DummyIQuantity : IQuantity { - public QuantityType Type => throw new NotImplementedException(); - public BaseDimensions Dimensions => throw new NotImplementedException(); public QuantityInfo QuantityInfo => throw new NotImplementedException(); public Enum Unit => throw new NotImplementedException(); - public double Value => 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([CanBeNull] IFormatProvider provider ) => throw new NotImplementedException(); - - public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix ) => throw new NotImplementedException(); + public string ToString(IFormatProvider? provider) => throw new NotImplementedException(); - public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args ) => throw new NotImplementedException(); + public string ToString(string? format, IFormatProvider? formatProvider) => 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(Enum unit, UnitConverter unitConverter) => throw new NotImplementedException(); - public IQuantity ToUnit(UnitSystem unitSystem ) => throw new NotImplementedException(); } } diff --git a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs index 034793650c..1345e425fe 100644 --- a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs +++ b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs @@ -277,130 +277,6 @@ public void QuantityInfo_IsSameAsStaticInfoProperty() Assertion(WarpingMomentOfInertia.Info, WarpingMomentOfInertia.Zero); } - [Fact] - public void Type_EqualsStaticQuantityTypeProperty() - { - void Assertion(QuantityType expected, IQuantity quantity) => Assert.Equal(expected, quantity.Type); - - Assertion(Acceleration.QuantityType, Acceleration.Zero); - Assertion(AmountOfSubstance.QuantityType, AmountOfSubstance.Zero); - Assertion(AmplitudeRatio.QuantityType, AmplitudeRatio.Zero); - Assertion(Angle.QuantityType, Angle.Zero); - Assertion(ApparentEnergy.QuantityType, ApparentEnergy.Zero); - Assertion(ApparentPower.QuantityType, ApparentPower.Zero); - Assertion(Area.QuantityType, Area.Zero); - Assertion(AreaDensity.QuantityType, AreaDensity.Zero); - Assertion(AreaMomentOfInertia.QuantityType, AreaMomentOfInertia.Zero); - Assertion(BitRate.QuantityType, BitRate.Zero); - Assertion(BrakeSpecificFuelConsumption.QuantityType, BrakeSpecificFuelConsumption.Zero); - Assertion(Capacitance.QuantityType, Capacitance.Zero); - Assertion(CoefficientOfThermalExpansion.QuantityType, CoefficientOfThermalExpansion.Zero); - Assertion(Compressibility.QuantityType, Compressibility.Zero); - Assertion(Density.QuantityType, Density.Zero); - Assertion(Duration.QuantityType, Duration.Zero); - Assertion(DynamicViscosity.QuantityType, DynamicViscosity.Zero); - Assertion(ElectricAdmittance.QuantityType, ElectricAdmittance.Zero); - Assertion(ElectricCharge.QuantityType, ElectricCharge.Zero); - Assertion(ElectricChargeDensity.QuantityType, ElectricChargeDensity.Zero); - Assertion(ElectricConductance.QuantityType, ElectricConductance.Zero); - Assertion(ElectricConductivity.QuantityType, ElectricConductivity.Zero); - Assertion(ElectricCurrent.QuantityType, ElectricCurrent.Zero); - Assertion(ElectricCurrentDensity.QuantityType, ElectricCurrentDensity.Zero); - Assertion(ElectricCurrentGradient.QuantityType, ElectricCurrentGradient.Zero); - Assertion(ElectricField.QuantityType, ElectricField.Zero); - Assertion(ElectricInductance.QuantityType, ElectricInductance.Zero); - Assertion(ElectricPotential.QuantityType, ElectricPotential.Zero); - Assertion(ElectricPotentialAc.QuantityType, ElectricPotentialAc.Zero); - Assertion(ElectricPotentialChangeRate.QuantityType, ElectricPotentialChangeRate.Zero); - Assertion(ElectricPotentialDc.QuantityType, ElectricPotentialDc.Zero); - Assertion(ElectricResistance.QuantityType, ElectricResistance.Zero); - Assertion(ElectricResistivity.QuantityType, ElectricResistivity.Zero); - Assertion(ElectricSurfaceChargeDensity.QuantityType, ElectricSurfaceChargeDensity.Zero); - Assertion(Energy.QuantityType, Energy.Zero); - Assertion(EnergyDensity.QuantityType, EnergyDensity.Zero); - Assertion(Entropy.QuantityType, Entropy.Zero); - Assertion(Force.QuantityType, Force.Zero); - Assertion(ForceChangeRate.QuantityType, ForceChangeRate.Zero); - Assertion(ForcePerLength.QuantityType, ForcePerLength.Zero); - Assertion(Frequency.QuantityType, Frequency.Zero); - Assertion(FuelEfficiency.QuantityType, FuelEfficiency.Zero); - Assertion(HeatFlux.QuantityType, HeatFlux.Zero); - Assertion(HeatTransferCoefficient.QuantityType, HeatTransferCoefficient.Zero); - Assertion(Illuminance.QuantityType, Illuminance.Zero); - Assertion(Information.QuantityType, Information.Zero); - Assertion(Irradiance.QuantityType, Irradiance.Zero); - Assertion(Irradiation.QuantityType, Irradiation.Zero); - Assertion(Jerk.QuantityType, Jerk.Zero); - Assertion(KinematicViscosity.QuantityType, KinematicViscosity.Zero); - Assertion(LapseRate.QuantityType, LapseRate.Zero); - Assertion(Length.QuantityType, Length.Zero); - Assertion(Level.QuantityType, Level.Zero); - Assertion(LinearDensity.QuantityType, LinearDensity.Zero); - Assertion(LinearPowerDensity.QuantityType, LinearPowerDensity.Zero); - Assertion(Luminance.QuantityType, Luminance.Zero); - Assertion(Luminosity.QuantityType, Luminosity.Zero); - Assertion(LuminousFlux.QuantityType, LuminousFlux.Zero); - Assertion(LuminousIntensity.QuantityType, LuminousIntensity.Zero); - Assertion(MagneticField.QuantityType, MagneticField.Zero); - Assertion(MagneticFlux.QuantityType, MagneticFlux.Zero); - Assertion(Magnetization.QuantityType, Magnetization.Zero); - Assertion(Mass.QuantityType, Mass.Zero); - Assertion(MassConcentration.QuantityType, MassConcentration.Zero); - Assertion(MassFlow.QuantityType, MassFlow.Zero); - Assertion(MassFlux.QuantityType, MassFlux.Zero); - Assertion(MassFraction.QuantityType, MassFraction.Zero); - Assertion(MassMomentOfInertia.QuantityType, MassMomentOfInertia.Zero); - Assertion(MolarEnergy.QuantityType, MolarEnergy.Zero); - Assertion(MolarEntropy.QuantityType, MolarEntropy.Zero); - Assertion(Molarity.QuantityType, Molarity.Zero); - Assertion(MolarMass.QuantityType, MolarMass.Zero); - Assertion(Permeability.QuantityType, Permeability.Zero); - Assertion(Permittivity.QuantityType, Permittivity.Zero); - Assertion(PorousMediumPermeability.QuantityType, PorousMediumPermeability.Zero); - Assertion(Power.QuantityType, Power.Zero); - Assertion(PowerDensity.QuantityType, PowerDensity.Zero); - Assertion(PowerRatio.QuantityType, PowerRatio.Zero); - Assertion(Pressure.QuantityType, Pressure.Zero); - Assertion(PressureChangeRate.QuantityType, PressureChangeRate.Zero); - Assertion(Ratio.QuantityType, Ratio.Zero); - Assertion(RatioChangeRate.QuantityType, RatioChangeRate.Zero); - Assertion(ReactiveEnergy.QuantityType, ReactiveEnergy.Zero); - Assertion(ReactivePower.QuantityType, ReactivePower.Zero); - Assertion(ReciprocalArea.QuantityType, ReciprocalArea.Zero); - Assertion(ReciprocalLength.QuantityType, ReciprocalLength.Zero); - Assertion(RelativeHumidity.QuantityType, RelativeHumidity.Zero); - Assertion(RotationalAcceleration.QuantityType, RotationalAcceleration.Zero); - Assertion(RotationalSpeed.QuantityType, RotationalSpeed.Zero); - Assertion(RotationalStiffness.QuantityType, RotationalStiffness.Zero); - Assertion(RotationalStiffnessPerLength.QuantityType, RotationalStiffnessPerLength.Zero); - Assertion(Scalar.QuantityType, Scalar.Zero); - Assertion(SolidAngle.QuantityType, SolidAngle.Zero); - Assertion(SpecificEnergy.QuantityType, SpecificEnergy.Zero); - Assertion(SpecificEntropy.QuantityType, SpecificEntropy.Zero); - Assertion(SpecificFuelConsumption.QuantityType, SpecificFuelConsumption.Zero); - Assertion(SpecificVolume.QuantityType, SpecificVolume.Zero); - Assertion(SpecificWeight.QuantityType, SpecificWeight.Zero); - Assertion(Speed.QuantityType, Speed.Zero); - Assertion(StandardVolumeFlow.QuantityType, StandardVolumeFlow.Zero); - Assertion(Temperature.QuantityType, Temperature.Zero); - Assertion(TemperatureChangeRate.QuantityType, TemperatureChangeRate.Zero); - Assertion(TemperatureDelta.QuantityType, TemperatureDelta.Zero); - Assertion(TemperatureGradient.QuantityType, TemperatureGradient.Zero); - Assertion(ThermalConductivity.QuantityType, ThermalConductivity.Zero); - Assertion(ThermalResistance.QuantityType, ThermalResistance.Zero); - Assertion(Torque.QuantityType, Torque.Zero); - Assertion(TorquePerLength.QuantityType, TorquePerLength.Zero); - Assertion(Turbidity.QuantityType, Turbidity.Zero); - Assertion(VitaminA.QuantityType, VitaminA.Zero); - Assertion(Volume.QuantityType, Volume.Zero); - Assertion(VolumeConcentration.QuantityType, VolumeConcentration.Zero); - Assertion(VolumeFlow.QuantityType, VolumeFlow.Zero); - Assertion(VolumeFlowPerArea.QuantityType, VolumeFlowPerArea.Zero); - Assertion(VolumePerLength.QuantityType, VolumePerLength.Zero); - Assertion(VolumetricHeatCapacity.QuantityType, VolumetricHeatCapacity.Zero); - Assertion(WarpingMomentOfInertia.QuantityType, WarpingMomentOfInertia.Zero); - } - [Fact] public void Dimensions_IsSameAsStaticBaseDimensions() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs index ddb68ee1c7..6645e64022 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class AccelerationTestsBase : QuantityTestsBase new object[] { AccelerationUnit.StandardGravity }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Acceleration((double)0.0, AccelerationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AccelerationUnit.MeterPerSecondSquared, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void Acceleration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Acceleration.Zero, quantityInfo.Zero); Assert.Equal("Acceleration", quantityInfo.Name); - Assert.Equal(QuantityType.Acceleration, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AccelerationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1009,7 +997,7 @@ public void ToUnit(AccelerationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1026,12 +1014,8 @@ public void ToUnit_WithSameUnits_AreEqual(AccelerationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AccelerationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Acceleration.Units.FirstOrDefault(u => u != Acceleration.BaseUnit && u != AccelerationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AccelerationUnit.Undefined) - fromUnit = Acceleration.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Acceleration.Units.Where(u => u != Acceleration.BaseUnit).DefaultIfEmpty(Acceleration.BaseUnit).FirstOrDefault(); var quantity = Acceleration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1120,49 +1104,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => meterpersecondsquared.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Acceleration.FromMetersPerSecondSquared(1); - var b = Acceleration.FromMetersPerSecondSquared(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Acceleration.FromMetersPerSecondSquared(1); - var b = Acceleration.FromMetersPerSecondSquared(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Acceleration.FromMetersPerSecondSquared(1); - object b = Acceleration.FromMetersPerSecondSquared(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1192,21 +1133,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(meterpersecondsquared.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AccelerationUnit.Undefined, Acceleration.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AccelerationUnit)).Cast(); foreach(var unit in units) { - if (unit == AccelerationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1220,8 +1152,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm/s²", new Acceleration(1, AccelerationUnit.CentimeterPerSecondSquared).ToString()); Assert.Equal("1 dm/s²", new Acceleration(1, AccelerationUnit.DecimeterPerSecondSquared).ToString()); @@ -1240,7 +1172,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1269,10 +1201,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m/s²", new Acceleration(0.123456, AccelerationUnit.MeterPerSecondSquared).ToString("s1")); Assert.Equal("0.12 m/s²", new Acceleration(0.123456, AccelerationUnit.MeterPerSecondSquared).ToString("s2")); Assert.Equal("0.123 m/s²", new Acceleration(0.123456, AccelerationUnit.MeterPerSecondSquared).ToString("s3")); @@ -1280,7 +1212,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1294,29 +1226,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m/s²", new Acceleration(0.123456, AccelerationUnit.MeterPerSecondSquared).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1436,13 +1367,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AccelerationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(QuantityType.Acceleration, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs index 2f3bcb7928..596218d543 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs @@ -114,12 +114,6 @@ public abstract partial class AmountOfSubstanceTestsBase : QuantityTestsBase new object[] { AmountOfSubstanceUnit.PoundMole }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new AmountOfSubstance((double)0.0, AmountOfSubstanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -128,7 +122,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AmountOfSubstanceUnit.Mole, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -172,14 +165,9 @@ public void AmountOfSubstance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(AmountOfSubstance.Zero, quantityInfo.Zero); Assert.Equal("AmountOfSubstance", quantityInfo.Name); - Assert.Equal(QuantityType.AmountOfSubstance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AmountOfSubstanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -685,7 +673,7 @@ public void ToUnit(AmountOfSubstanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -702,12 +690,8 @@ public void ToUnit_WithSameUnits_AreEqual(AmountOfSubstanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmountOfSubstanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = AmountOfSubstance.Units.FirstOrDefault(u => u != AmountOfSubstance.BaseUnit && u != AmountOfSubstanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AmountOfSubstanceUnit.Undefined) - fromUnit = AmountOfSubstance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = AmountOfSubstance.Units.Where(u => u != AmountOfSubstance.BaseUnit).DefaultIfEmpty(AmountOfSubstance.BaseUnit).FirstOrDefault(); var quantity = AmountOfSubstance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -797,49 +781,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => mole.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = AmountOfSubstance.FromMoles(1); - var b = AmountOfSubstance.FromMoles(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = AmountOfSubstance.FromMoles(1); - var b = AmountOfSubstance.FromMoles(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = AmountOfSubstance.FromMoles(1); - object b = AmountOfSubstance.FromMoles(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -869,21 +810,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(mole.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AmountOfSubstanceUnit.Undefined, AmountOfSubstance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast(); foreach(var unit in units) { - if (unit == AmountOfSubstanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -897,8 +829,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cmol", new AmountOfSubstance(1, AmountOfSubstanceUnit.Centimole).ToString()); Assert.Equal("1 clbmol", new AmountOfSubstance(1, AmountOfSubstanceUnit.CentipoundMole).ToString()); @@ -918,7 +850,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -948,10 +880,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 mol", new AmountOfSubstance(0.123456, AmountOfSubstanceUnit.Mole).ToString("s1")); Assert.Equal("0.12 mol", new AmountOfSubstance(0.123456, AmountOfSubstanceUnit.Mole).ToString("s2")); Assert.Equal("0.123 mol", new AmountOfSubstance(0.123456, AmountOfSubstanceUnit.Mole).ToString("s3")); @@ -959,7 +891,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -973,29 +905,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 mol", new AmountOfSubstance(0.123456, AmountOfSubstanceUnit.Mole).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1115,13 +1046,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AmountOfSubstanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(QuantityType.AmountOfSubstance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs index 6f87aceee0..236f6e77e2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class AmplitudeRatioTestsBase : QuantityTestsBase new object[] { AmplitudeRatioUnit.DecibelVolt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new AmplitudeRatio((double)0.0, AmplitudeRatioUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AmplitudeRatioUnit.DecibelVolt, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void AmplitudeRatio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(AmplitudeRatio.Zero, quantityInfo.Zero); Assert.Equal("AmplitudeRatio", quantityInfo.Name); - Assert.Equal(QuantityType.AmplitudeRatio, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AmplitudeRatioUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(AmplitudeRatioUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(AmplitudeRatioUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmplitudeRatioUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = AmplitudeRatio.Units.FirstOrDefault(u => u != AmplitudeRatio.BaseUnit && u != AmplitudeRatioUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AmplitudeRatioUnit.Undefined) - fromUnit = AmplitudeRatio.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = AmplitudeRatio.Units.Where(u => u != AmplitudeRatio.BaseUnit).DefaultIfEmpty(AmplitudeRatio.BaseUnit).FirstOrDefault(); var quantity = AmplitudeRatio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -438,49 +422,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decibelvolt.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = AmplitudeRatio.FromDecibelVolts(1); - var b = AmplitudeRatio.FromDecibelVolts(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = AmplitudeRatio.FromDecibelVolts(1); - var b = AmplitudeRatio.FromDecibelVolts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = AmplitudeRatio.FromDecibelVolts(1); - object b = AmplitudeRatio.FromDecibelVolts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -510,21 +451,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decibelvolt.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AmplitudeRatioUnit.Undefined, AmplitudeRatio.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast(); foreach(var unit in units) { - if (unit == AmplitudeRatioUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -538,8 +470,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 dBµV", new AmplitudeRatio(1, AmplitudeRatioUnit.DecibelMicrovolt).ToString()); Assert.Equal("1 dBmV", new AmplitudeRatio(1, AmplitudeRatioUnit.DecibelMillivolt).ToString()); @@ -548,7 +480,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -567,10 +499,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 dBV", new AmplitudeRatio(0.123456, AmplitudeRatioUnit.DecibelVolt).ToString("s1")); Assert.Equal("0.12 dBV", new AmplitudeRatio(0.123456, AmplitudeRatioUnit.DecibelVolt).ToString("s2")); Assert.Equal("0.123 dBV", new AmplitudeRatio(0.123456, AmplitudeRatioUnit.DecibelVolt).ToString("s3")); @@ -578,7 +510,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -592,29 +524,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 dBV", new AmplitudeRatio(0.123456, AmplitudeRatioUnit.DecibelVolt).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -734,13 +665,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AmplitudeRatioUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(QuantityType.AmplitudeRatio, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs index 384698cce3..ed0c60952b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs @@ -118,12 +118,6 @@ public abstract partial class AngleTestsBase : QuantityTestsBase new object[] { AngleUnit.Tilt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Angle((double)0.0, AngleUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -132,7 +126,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AngleUnit.Degree, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -176,14 +169,9 @@ public void Angle_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Angle.Zero, quantityInfo.Zero); Assert.Equal("Angle", quantityInfo.Name); - Assert.Equal(QuantityType.Angle, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AngleUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1269,7 +1257,7 @@ public void ToUnit(AngleUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1286,12 +1274,8 @@ public void ToUnit_WithSameUnits_AreEqual(AngleUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AngleUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Angle.Units.FirstOrDefault(u => u != Angle.BaseUnit && u != AngleUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AngleUnit.Undefined) - fromUnit = Angle.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Angle.Units.Where(u => u != Angle.BaseUnit).DefaultIfEmpty(Angle.BaseUnit).FirstOrDefault(); var quantity = Angle.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1382,49 +1366,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => degree.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Angle.FromDegrees(1); - var b = Angle.FromDegrees(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Angle.FromDegrees(1); - var b = Angle.FromDegrees(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Angle.FromDegrees(1); - object b = Angle.FromDegrees(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1454,21 +1395,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(degree.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AngleUnit.Undefined, Angle.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AngleUnit)).Cast(); foreach(var unit in units) { - if (unit == AngleUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1482,8 +1414,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 '", new Angle(1, AngleUnit.Arcminute).ToString()); Assert.Equal("1 ″", new Angle(1, AngleUnit.Arcsecond).ToString()); @@ -1504,7 +1436,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1535,10 +1467,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 °", new Angle(0.123456, AngleUnit.Degree).ToString("s1")); Assert.Equal("0.12 °", new Angle(0.123456, AngleUnit.Degree).ToString("s2")); Assert.Equal("0.123 °", new Angle(0.123456, AngleUnit.Degree).ToString("s3")); @@ -1546,7 +1478,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1560,29 +1492,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 °", new Angle(0.123456, AngleUnit.Degree).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Angle.FromDegrees(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Angle.FromDegrees(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Angle.FromDegrees(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1702,13 +1633,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AngleUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Angle.FromDegrees(1.0); - Assert.Equal(QuantityType.Angle, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs index 4129c0b580..a39613c3a7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentEnergyTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class ApparentEnergyTestsBase : QuantityTestsBase new object[] { ApparentEnergyUnit.VoltampereHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ApparentEnergy((double)0.0, ApparentEnergyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ApparentEnergyUnit.VoltampereHour, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void ApparentEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ApparentEnergy.Zero, quantityInfo.Zero); Assert.Equal("ApparentEnergy", quantityInfo.Name); - Assert.Equal(QuantityType.ApparentEnergy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ApparentEnergyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(ApparentEnergyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(ApparentEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ApparentEnergyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ApparentEnergy.Units.FirstOrDefault(u => u != ApparentEnergy.BaseUnit && u != ApparentEnergyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ApparentEnergyUnit.Undefined) - fromUnit = ApparentEnergy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ApparentEnergy.Units.Where(u => u != ApparentEnergy.BaseUnit).DefaultIfEmpty(ApparentEnergy.BaseUnit).FirstOrDefault(); var quantity = ApparentEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltamperehour.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ApparentEnergy.FromVoltampereHours(1); - var b = ApparentEnergy.FromVoltampereHours(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ApparentEnergy.FromVoltampereHours(1); - var b = ApparentEnergy.FromVoltampereHours(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ApparentEnergy.FromVoltampereHours(1); - object b = ApparentEnergy.FromVoltampereHours(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltamperehour.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ApparentEnergyUnit.Undefined, ApparentEnergy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast(); foreach(var unit in units) { - if (unit == ApparentEnergyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kVAh", new ApparentEnergy(1, ApparentEnergyUnit.KilovoltampereHour).ToString()); Assert.Equal("1 MVAh", new ApparentEnergy(1, ApparentEnergyUnit.MegavoltampereHour).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 VAh", new ApparentEnergy(0.123456, ApparentEnergyUnit.VoltampereHour).ToString("s1")); Assert.Equal("0.12 VAh", new ApparentEnergy(0.123456, ApparentEnergyUnit.VoltampereHour).ToString("s2")); Assert.Equal("0.123 VAh", new ApparentEnergy(0.123456, ApparentEnergyUnit.VoltampereHour).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 VAh", new ApparentEnergy(0.123456, ApparentEnergyUnit.VoltampereHour).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ApparentEnergyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(QuantityType.ApparentEnergy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs index bc93ea85e7..5075cc0c55 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ApparentPowerTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class ApparentPowerTestsBase : QuantityTestsBase new object[] { ApparentPowerUnit.Voltampere }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ApparentPower((double)0.0, ApparentPowerUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ApparentPowerUnit.Voltampere, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void ApparentPower_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ApparentPower.Zero, quantityInfo.Zero); Assert.Equal("ApparentPower", quantityInfo.Name); - Assert.Equal(QuantityType.ApparentPower, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ApparentPowerUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(ApparentPowerUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(ApparentPowerUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ApparentPowerUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ApparentPower.Units.FirstOrDefault(u => u != ApparentPower.BaseUnit && u != ApparentPowerUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ApparentPowerUnit.Undefined) - fromUnit = ApparentPower.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ApparentPower.Units.Where(u => u != ApparentPower.BaseUnit).DefaultIfEmpty(ApparentPower.BaseUnit).FirstOrDefault(); var quantity = ApparentPower.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltampere.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ApparentPower.FromVoltamperes(1); - var b = ApparentPower.FromVoltamperes(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ApparentPower.FromVoltamperes(1); - var b = ApparentPower.FromVoltamperes(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ApparentPower.FromVoltamperes(1); - object b = ApparentPower.FromVoltamperes(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltampere.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ApparentPowerUnit.Undefined, ApparentPower.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ApparentPowerUnit)).Cast(); foreach(var unit in units) { - if (unit == ApparentPowerUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 GVA", new ApparentPower(1, ApparentPowerUnit.Gigavoltampere).ToString()); Assert.Equal("1 kVA", new ApparentPower(1, ApparentPowerUnit.Kilovoltampere).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 VA", new ApparentPower(0.123456, ApparentPowerUnit.Voltampere).ToString("s1")); Assert.Equal("0.12 VA", new ApparentPower(0.123456, ApparentPowerUnit.Voltampere).ToString("s2")); Assert.Equal("0.123 VA", new ApparentPower(0.123456, ApparentPowerUnit.Voltampere).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 VA", new ApparentPower(0.123456, ApparentPowerUnit.Voltampere).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ApparentPowerUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ApparentPower.FromVoltamperes(1.0); - Assert.Equal(QuantityType.ApparentPower, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs index 7bc0203a1c..bbe146a68a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class AreaDensityTestsBase : QuantityTestsBase new object[] { AreaDensityUnit.MilligramPerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new AreaDensity((double)0.0, AreaDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AreaDensityUnit.KilogramPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void AreaDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(AreaDensity.Zero, quantityInfo.Zero); Assert.Equal("AreaDensity", quantityInfo.Name); - Assert.Equal(QuantityType.AreaDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AreaDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -323,7 +311,7 @@ public void ToUnit(AreaDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -340,12 +328,8 @@ public void ToUnit_WithSameUnits_AreEqual(AreaDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = AreaDensity.Units.FirstOrDefault(u => u != AreaDensity.BaseUnit && u != AreaDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AreaDensityUnit.Undefined) - fromUnit = AreaDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = AreaDensity.Units.Where(u => u != AreaDensity.BaseUnit).DefaultIfEmpty(AreaDensity.BaseUnit).FirstOrDefault(); var quantity = AreaDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -423,49 +407,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogrampersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = AreaDensity.FromKilogramsPerSquareMeter(1); - var b = AreaDensity.FromKilogramsPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = AreaDensity.FromKilogramsPerSquareMeter(1); - var b = AreaDensity.FromKilogramsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = AreaDensity.FromKilogramsPerSquareMeter(1); - object b = AreaDensity.FromKilogramsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -495,21 +436,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AreaDensityUnit.Undefined, AreaDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AreaDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == AreaDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -523,8 +455,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 g/m²", new AreaDensity(1, AreaDensityUnit.GramPerSquareMeter).ToString()); Assert.Equal("1 kg/m²", new AreaDensity(1, AreaDensityUnit.KilogramPerSquareMeter).ToString()); @@ -532,7 +464,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -550,10 +482,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg/m²", new AreaDensity(0.123456, AreaDensityUnit.KilogramPerSquareMeter).ToString("s1")); Assert.Equal("0.12 kg/m²", new AreaDensity(0.123456, AreaDensityUnit.KilogramPerSquareMeter).ToString("s2")); Assert.Equal("0.123 kg/m²", new AreaDensity(0.123456, AreaDensityUnit.KilogramPerSquareMeter).ToString("s3")); @@ -561,7 +493,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -575,29 +507,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg/m²", new AreaDensity(0.123456, AreaDensityUnit.KilogramPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -717,13 +648,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AreaDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(QuantityType.AreaDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs index 314f377977..9a0986fbbd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class AreaMomentOfInertiaTestsBase : QuantityTestsBase new object[] { AreaMomentOfInertiaUnit.MillimeterToTheFourth }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new AreaMomentOfInertia((double)0.0, AreaMomentOfInertiaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AreaMomentOfInertiaUnit.MeterToTheFourth, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void AreaMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(AreaMomentOfInertia.Zero, quantityInfo.Zero); Assert.Equal("AreaMomentOfInertia", quantityInfo.Name); - Assert.Equal(QuantityType.AreaMomentOfInertia, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AreaMomentOfInertiaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -545,7 +533,7 @@ public void ToUnit(AreaMomentOfInertiaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -562,12 +550,8 @@ public void ToUnit_WithSameUnits_AreEqual(AreaMomentOfInertiaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaMomentOfInertiaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = AreaMomentOfInertia.Units.FirstOrDefault(u => u != AreaMomentOfInertia.BaseUnit && u != AreaMomentOfInertiaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AreaMomentOfInertiaUnit.Undefined) - fromUnit = AreaMomentOfInertia.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = AreaMomentOfInertia.Units.Where(u => u != AreaMomentOfInertia.BaseUnit).DefaultIfEmpty(AreaMomentOfInertia.BaseUnit).FirstOrDefault(); var quantity = AreaMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -648,49 +632,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => metertothefourth.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = AreaMomentOfInertia.FromMetersToTheFourth(1); - var b = AreaMomentOfInertia.FromMetersToTheFourth(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = AreaMomentOfInertia.FromMetersToTheFourth(1); - var b = AreaMomentOfInertia.FromMetersToTheFourth(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = AreaMomentOfInertia.FromMetersToTheFourth(1); - object b = AreaMomentOfInertia.FromMetersToTheFourth(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -720,21 +661,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(metertothefourth.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AreaMomentOfInertiaUnit.Undefined, AreaMomentOfInertia.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast(); foreach(var unit in units) { - if (unit == AreaMomentOfInertiaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -748,8 +680,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm⁴", new AreaMomentOfInertia(1, AreaMomentOfInertiaUnit.CentimeterToTheFourth).ToString()); Assert.Equal("1 dm⁴", new AreaMomentOfInertia(1, AreaMomentOfInertiaUnit.DecimeterToTheFourth).ToString()); @@ -760,7 +692,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -781,10 +713,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m⁴", new AreaMomentOfInertia(0.123456, AreaMomentOfInertiaUnit.MeterToTheFourth).ToString("s1")); Assert.Equal("0.12 m⁴", new AreaMomentOfInertia(0.123456, AreaMomentOfInertiaUnit.MeterToTheFourth).ToString("s2")); Assert.Equal("0.123 m⁴", new AreaMomentOfInertia(0.123456, AreaMomentOfInertiaUnit.MeterToTheFourth).ToString("s3")); @@ -792,7 +724,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -806,29 +738,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m⁴", new AreaMomentOfInertia(0.123456, AreaMomentOfInertiaUnit.MeterToTheFourth).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -948,13 +879,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AreaMomentOfInertiaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(QuantityType.AreaMomentOfInertia, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs index 64a44af040..73847cecf7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class AreaTestsBase : QuantityTestsBase new object[] { AreaUnit.UsSurveySquareFoot }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Area((double)0.0, AreaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(AreaUnit.SquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void Area_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Area.Zero, quantityInfo.Zero); Assert.Equal("Area", quantityInfo.Name); - Assert.Equal(QuantityType.Area, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {AreaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1299,7 +1287,7 @@ public void ToUnit(AreaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1316,12 +1304,8 @@ public void ToUnit_WithSameUnits_AreEqual(AreaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Area.Units.FirstOrDefault(u => u != Area.BaseUnit && u != AreaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == AreaUnit.Undefined) - fromUnit = Area.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Area.Units.Where(u => u != Area.BaseUnit).DefaultIfEmpty(Area.BaseUnit).FirstOrDefault(); var quantity = Area.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1410,49 +1394,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => squaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Area.FromSquareMeters(1); - var b = Area.FromSquareMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Area.FromSquareMeters(1); - var b = Area.FromSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Area.FromSquareMeters(1); - object b = Area.FromSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1482,21 +1423,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(squaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(AreaUnit.Undefined, Area.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(AreaUnit)).Cast(); foreach(var unit in units) { - if (unit == AreaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1510,8 +1442,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 ac", new Area(1, AreaUnit.Acre).ToString()); Assert.Equal("1 ha", new Area(1, AreaUnit.Hectare).ToString()); @@ -1530,7 +1462,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1559,10 +1491,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m²", new Area(0.123456, AreaUnit.SquareMeter).ToString("s1")); Assert.Equal("0.12 m²", new Area(0.123456, AreaUnit.SquareMeter).ToString("s2")); Assert.Equal("0.123 m²", new Area(0.123456, AreaUnit.SquareMeter).ToString("s3")); @@ -1570,7 +1502,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1584,29 +1516,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m²", new Area(0.123456, AreaUnit.SquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Area.FromSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1726,13 +1657,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AreaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(QuantityType.Area, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs index 6331fd8117..3aff01b03f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs @@ -38,63 +38,63 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class BitRateTestsBase : QuantityTestsBase { - protected abstract double BitsPerSecondInOneBitPerSecond { get; } - protected abstract double BytesPerSecondInOneBitPerSecond { get; } - protected abstract double ExabitsPerSecondInOneBitPerSecond { get; } - protected abstract double ExabytesPerSecondInOneBitPerSecond { get; } - protected abstract double ExbibitsPerSecondInOneBitPerSecond { get; } - protected abstract double ExbibytesPerSecondInOneBitPerSecond { get; } - protected abstract double GibibitsPerSecondInOneBitPerSecond { get; } - protected abstract double GibibytesPerSecondInOneBitPerSecond { get; } - protected abstract double GigabitsPerSecondInOneBitPerSecond { get; } - protected abstract double GigabytesPerSecondInOneBitPerSecond { get; } - protected abstract double KibibitsPerSecondInOneBitPerSecond { get; } - protected abstract double KibibytesPerSecondInOneBitPerSecond { get; } - protected abstract double KilobitsPerSecondInOneBitPerSecond { get; } - protected abstract double KilobytesPerSecondInOneBitPerSecond { get; } - protected abstract double MebibitsPerSecondInOneBitPerSecond { get; } - protected abstract double MebibytesPerSecondInOneBitPerSecond { get; } - protected abstract double MegabitsPerSecondInOneBitPerSecond { get; } - protected abstract double MegabytesPerSecondInOneBitPerSecond { get; } - protected abstract double PebibitsPerSecondInOneBitPerSecond { get; } - protected abstract double PebibytesPerSecondInOneBitPerSecond { get; } - protected abstract double PetabitsPerSecondInOneBitPerSecond { get; } - protected abstract double PetabytesPerSecondInOneBitPerSecond { get; } - protected abstract double TebibitsPerSecondInOneBitPerSecond { get; } - protected abstract double TebibytesPerSecondInOneBitPerSecond { get; } - protected abstract double TerabitsPerSecondInOneBitPerSecond { get; } - protected abstract double TerabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal BitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal BytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExbibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal ExbibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal GibibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal GibibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal GigabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal GigabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal KibibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal KibibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal KilobitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal KilobytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal MebibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal MebibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal MegabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal MegabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal PebibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal PebibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal PetabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal PetabytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal TebibitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal TebibytesPerSecondInOneBitPerSecond { get; } + protected abstract decimal TerabitsPerSecondInOneBitPerSecond { get; } + protected abstract decimal TerabytesPerSecondInOneBitPerSecond { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double BytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExbibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double ExbibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double GibibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double GibibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double GigabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double GigabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double KibibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KibibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilobitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double KilobytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MebibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MebibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double MegabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double PebibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PebibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double PetabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double PetabytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double TebibitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double TebibytesPerSecondTolerance { get { return 1e-5; } } - protected virtual double TerabitsPerSecondTolerance { get { return 1e-5; } } - protected virtual double TerabytesPerSecondTolerance { get { return 1e-5; } } + protected virtual decimal BitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal BytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal ExabitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal ExabytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal ExbibitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal ExbibytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal GibibitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal GibibytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal GigabitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal GigabytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal KibibitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal KibibytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal KilobitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal KilobytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal MebibitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal MebibytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal MegabitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal MegabytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal PebibitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal PebibytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal PetabitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal PetabytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal TebibitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal TebibytesPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal TerabitsPerSecondTolerance { get { return 1e-9m; } } + protected virtual decimal TerabytesPerSecondTolerance { get { return 1e-9m; } } // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(BitRateUnit unit) + protected (decimal UnitsInBaseUnit, decimal Tolerence) GetConversionFactor(BitRateUnit unit) { return unit switch { @@ -158,12 +158,6 @@ public abstract partial class BitRateTestsBase : QuantityTestsBase new object[] { BitRateUnit.TerabytePerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new BitRate((decimal)0.0, BitRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -173,7 +167,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(BitRateUnit.BitPerSecond, quantity.Unit); } - [Fact] public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException() { @@ -204,14 +197,9 @@ public void BitRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(BitRate.Zero, quantityInfo.Zero); Assert.Equal("BitRate", quantityInfo.Name); - Assert.Equal(QuantityType.BitRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {BitRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1368,7 +1356,7 @@ public void ToUnit(BitRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1385,12 +1373,8 @@ public void ToUnit_WithSameUnits_AreEqual(BitRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BitRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = BitRate.Units.FirstOrDefault(u => u != BitRate.BaseUnit && u != BitRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == BitRateUnit.Undefined) - fromUnit = BitRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = BitRate.Units.Where(u => u != BitRate.BaseUnit).DefaultIfEmpty(BitRate.BaseUnit).FirstOrDefault(); var quantity = BitRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1491,49 +1475,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => bitpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = BitRate.FromBitsPerSecond(1); - var b = BitRate.FromBitsPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = BitRate.FromBitsPerSecond(1); - var b = BitRate.FromBitsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = BitRate.FromBitsPerSecond(1); - object b = BitRate.FromBitsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1563,21 +1504,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(bitpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(BitRateUnit.Undefined, BitRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(BitRateUnit)).Cast(); foreach(var unit in units) { - if (unit == BitRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1591,8 +1523,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 bit/s", new BitRate(1, BitRateUnit.BitPerSecond).ToString()); Assert.Equal("1 B/s", new BitRate(1, BitRateUnit.BytePerSecond).ToString()); @@ -1623,7 +1555,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1664,10 +1596,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 bit/s", new BitRate(0.123456m, BitRateUnit.BitPerSecond).ToString("s1")); Assert.Equal("0.12 bit/s", new BitRate(0.123456m, BitRateUnit.BitPerSecond).ToString("s2")); Assert.Equal("0.123 bit/s", new BitRate(0.123456m, BitRateUnit.BitPerSecond).ToString("s3")); @@ -1675,7 +1607,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1689,29 +1621,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 bit/s", new BitRate(0.123456m, BitRateUnit.BitPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1831,13 +1762,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(BitRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(QuantityType.BitRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs index e85a982bf6..571b043d93 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class BrakeSpecificFuelConsumptionTestsBase : QuantityTe new object[] { BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new BrakeSpecificFuelConsumption((double)0.0, BrakeSpecificFuelConsumptionUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void BrakeSpecificFuelConsumption_QuantityInfo_ReturnsQuantityInfoDescrib Assert.Equal(BrakeSpecificFuelConsumption.Zero, quantityInfo.Zero); Assert.Equal("BrakeSpecificFuelConsumption", quantityInfo.Name); - Assert.Equal(QuantityType.BrakeSpecificFuelConsumption, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {BrakeSpecificFuelConsumptionUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(BrakeSpecificFuelConsumptionUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(BrakeSpecificFuelConsumptionUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BrakeSpecificFuelConsumptionUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = BrakeSpecificFuelConsumption.Units.FirstOrDefault(u => u != BrakeSpecificFuelConsumption.BaseUnit && u != BrakeSpecificFuelConsumptionUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == BrakeSpecificFuelConsumptionUnit.Undefined) - fromUnit = BrakeSpecificFuelConsumption.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = BrakeSpecificFuelConsumption.Units.Where(u => u != BrakeSpecificFuelConsumption.BaseUnit).DefaultIfEmpty(BrakeSpecificFuelConsumption.BaseUnit).FirstOrDefault(); var quantity = BrakeSpecificFuelConsumption.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogramperjoule.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - var b = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - var b = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - object b = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogramperjoule.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(BrakeSpecificFuelConsumptionUnit.Undefined, BrakeSpecificFuelConsumption.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast(); foreach(var unit in units) { - if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 g/kWh", new BrakeSpecificFuelConsumption(1, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour).ToString()); Assert.Equal("1 kg/J", new BrakeSpecificFuelConsumption(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg/J", new BrakeSpecificFuelConsumption(0.123456, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule).ToString("s1")); Assert.Equal("0.12 kg/J", new BrakeSpecificFuelConsumption(0.123456, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule).ToString("s2")); Assert.Equal("0.123 kg/J", new BrakeSpecificFuelConsumption(0.123456, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg/J", new BrakeSpecificFuelConsumption(0.123456, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(BrakeSpecificFuelConsumptionUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(QuantityType.BrakeSpecificFuelConsumption, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs index a87e6e5ff9..1e7a762a4c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CapacitanceTestsBase.g.cs @@ -82,12 +82,6 @@ public abstract partial class CapacitanceTestsBase : QuantityTestsBase new object[] { CapacitanceUnit.Picofarad }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Capacitance((double)0.0, CapacitanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -96,7 +90,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(CapacitanceUnit.Farad, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -140,14 +133,9 @@ public void Capacitance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Capacitance.Zero, quantityInfo.Zero); Assert.Equal("Capacitance", quantityInfo.Name); - Assert.Equal(QuantityType.Capacitance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {CapacitanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -413,7 +401,7 @@ public void ToUnit(CapacitanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -430,12 +418,8 @@ public void ToUnit_WithSameUnits_AreEqual(CapacitanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CapacitanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Capacitance.Units.FirstOrDefault(u => u != Capacitance.BaseUnit && u != CapacitanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == CapacitanceUnit.Undefined) - fromUnit = Capacitance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Capacitance.Units.Where(u => u != Capacitance.BaseUnit).DefaultIfEmpty(Capacitance.BaseUnit).FirstOrDefault(); var quantity = Capacitance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -517,49 +501,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => farad.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Capacitance.FromFarads(1); - var b = Capacitance.FromFarads(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Capacitance.FromFarads(1); - var b = Capacitance.FromFarads(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Capacitance.FromFarads(1); - object b = Capacitance.FromFarads(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -589,21 +530,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(farad.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(CapacitanceUnit.Undefined, Capacitance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(CapacitanceUnit)).Cast(); foreach(var unit in units) { - if (unit == CapacitanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -617,8 +549,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 F", new Capacitance(1, CapacitanceUnit.Farad).ToString()); Assert.Equal("1 kF", new Capacitance(1, CapacitanceUnit.Kilofarad).ToString()); @@ -630,7 +562,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -652,10 +584,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 F", new Capacitance(0.123456, CapacitanceUnit.Farad).ToString("s1")); Assert.Equal("0.12 F", new Capacitance(0.123456, CapacitanceUnit.Farad).ToString("s2")); Assert.Equal("0.123 F", new Capacitance(0.123456, CapacitanceUnit.Farad).ToString("s3")); @@ -663,7 +595,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -677,29 +609,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 F", new Capacitance(0.123456, CapacitanceUnit.Farad).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Capacitance.FromFarads(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Capacitance.FromFarads(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Capacitance.FromFarads(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -819,13 +750,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(CapacitanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Capacitance.FromFarads(1.0); - Assert.Equal(QuantityType.Capacitance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs index 30c9f37e61..fb81601d3e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class CoefficientOfThermalExpansionTestsBase : QuantityT new object[] { CoefficientOfThermalExpansionUnit.InverseKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new CoefficientOfThermalExpansion((double)0.0, CoefficientOfThermalExpansionUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(CoefficientOfThermalExpansionUnit.InverseKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void CoefficientOfThermalExpansion_QuantityInfo_ReturnsQuantityInfoDescri Assert.Equal(CoefficientOfThermalExpansion.Zero, quantityInfo.Zero); Assert.Equal("CoefficientOfThermalExpansion", quantityInfo.Name); - Assert.Equal(QuantityType.CoefficientOfThermalExpansion, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {CoefficientOfThermalExpansionUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -371,7 +359,7 @@ public void ToUnit(CoefficientOfThermalExpansionUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -388,12 +376,8 @@ public void ToUnit_WithSameUnits_AreEqual(CoefficientOfThermalExpansionUnit unit [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CoefficientOfThermalExpansionUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = CoefficientOfThermalExpansion.Units.FirstOrDefault(u => u != CoefficientOfThermalExpansion.BaseUnit && u != CoefficientOfThermalExpansionUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == CoefficientOfThermalExpansionUnit.Undefined) - fromUnit = CoefficientOfThermalExpansion.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = CoefficientOfThermalExpansion.Units.Where(u => u != CoefficientOfThermalExpansion.BaseUnit).DefaultIfEmpty(CoefficientOfThermalExpansion.BaseUnit).FirstOrDefault(); var quantity = CoefficientOfThermalExpansion.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -471,49 +455,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => inversekelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = CoefficientOfThermalExpansion.FromInverseKelvin(1); - var b = CoefficientOfThermalExpansion.FromInverseKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = CoefficientOfThermalExpansion.FromInverseKelvin(1); - var b = CoefficientOfThermalExpansion.FromInverseKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = CoefficientOfThermalExpansion.FromInverseKelvin(1); - object b = CoefficientOfThermalExpansion.FromInverseKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -543,21 +484,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(inversekelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(CoefficientOfThermalExpansionUnit.Undefined, CoefficientOfThermalExpansion.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast(); foreach(var unit in units) { - if (unit == CoefficientOfThermalExpansionUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -571,8 +503,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 °C⁻¹", new CoefficientOfThermalExpansion(1, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius).ToString()); Assert.Equal("1 °F⁻¹", new CoefficientOfThermalExpansion(1, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit).ToString()); @@ -580,7 +512,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -598,10 +530,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 K⁻¹", new CoefficientOfThermalExpansion(0.123456, CoefficientOfThermalExpansionUnit.InverseKelvin).ToString("s1")); Assert.Equal("0.12 K⁻¹", new CoefficientOfThermalExpansion(0.123456, CoefficientOfThermalExpansionUnit.InverseKelvin).ToString("s2")); Assert.Equal("0.123 K⁻¹", new CoefficientOfThermalExpansion(0.123456, CoefficientOfThermalExpansionUnit.InverseKelvin).ToString("s3")); @@ -609,7 +541,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -623,29 +555,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 K⁻¹", new CoefficientOfThermalExpansion(0.123456, CoefficientOfThermalExpansionUnit.InverseKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -765,13 +696,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(CoefficientOfThermalExpansionUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = CoefficientOfThermalExpansion.FromInverseKelvin(1.0); - Assert.Equal(QuantityType.CoefficientOfThermalExpansion, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs index dd2418e8f5..64e8d5643a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs @@ -82,12 +82,6 @@ public abstract partial class CompressibilityTestsBase : QuantityTestsBase new object[] { CompressibilityUnit.InversePoundForcePerSquareInch }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Compressibility((double)0.0, CompressibilityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -96,7 +90,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(CompressibilityUnit.InversePascal, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -140,14 +133,9 @@ public void Compressibility_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Compressibility.Zero, quantityInfo.Zero); Assert.Equal("Compressibility", quantityInfo.Name); - Assert.Equal(QuantityType.Compressibility, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {CompressibilityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -603,7 +591,7 @@ public void ToUnit(CompressibilityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -620,12 +608,8 @@ public void ToUnit_WithSameUnits_AreEqual(CompressibilityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CompressibilityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Compressibility.Units.FirstOrDefault(u => u != Compressibility.BaseUnit && u != CompressibilityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == CompressibilityUnit.Undefined) - fromUnit = Compressibility.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Compressibility.Units.Where(u => u != Compressibility.BaseUnit).DefaultIfEmpty(Compressibility.BaseUnit).FirstOrDefault(); var quantity = Compressibility.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -707,49 +691,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => inversepascal.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Compressibility.FromInversePascals(1); - var b = Compressibility.FromInversePascals(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Compressibility.FromInversePascals(1); - var b = Compressibility.FromInversePascals(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Compressibility.FromInversePascals(1); - object b = Compressibility.FromInversePascals(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -779,21 +720,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(inversepascal.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(CompressibilityUnit.Undefined, Compressibility.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(CompressibilityUnit)).Cast(); foreach(var unit in units) { - if (unit == CompressibilityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -807,8 +739,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 atm⁻¹", new Compressibility(1, CompressibilityUnit.InverseAtmosphere).ToString()); Assert.Equal("1 bar⁻¹", new Compressibility(1, CompressibilityUnit.InverseBar).ToString()); @@ -820,7 +752,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -842,10 +774,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Pa⁻¹", new Compressibility(0.123456, CompressibilityUnit.InversePascal).ToString("s1")); Assert.Equal("0.12 Pa⁻¹", new Compressibility(0.123456, CompressibilityUnit.InversePascal).ToString("s2")); Assert.Equal("0.123 Pa⁻¹", new Compressibility(0.123456, CompressibilityUnit.InversePascal).ToString("s3")); @@ -853,7 +785,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -867,29 +799,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Pa⁻¹", new Compressibility(0.123456, CompressibilityUnit.InversePascal).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Compressibility.FromInversePascals(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1009,13 +940,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(CompressibilityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(QuantityType.Compressibility, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs index cb32ec5ce0..e431d4a02b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs @@ -258,12 +258,6 @@ public abstract partial class DensityTestsBase : QuantityTestsBase new object[] { DensityUnit.TonnePerCubicMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Density((double)0.0, DensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -272,7 +266,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(DensityUnit.KilogramPerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -316,14 +309,9 @@ public void Density_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Density.Zero, quantityInfo.Zero); Assert.Equal("Density", quantityInfo.Name); - Assert.Equal(QuantityType.Density, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {DensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2027,7 +2015,7 @@ public void ToUnit(DensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2044,12 +2032,8 @@ public void ToUnit_WithSameUnits_AreEqual(DensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Density.Units.FirstOrDefault(u => u != Density.BaseUnit && u != DensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == DensityUnit.Undefined) - fromUnit = Density.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Density.Units.Where(u => u != Density.BaseUnit).DefaultIfEmpty(Density.BaseUnit).FirstOrDefault(); var quantity = Density.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2175,49 +2159,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogrampercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Density.FromKilogramsPerCubicMeter(1); - var b = Density.FromKilogramsPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Density.FromKilogramsPerCubicMeter(1); - var b = Density.FromKilogramsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Density.FromKilogramsPerCubicMeter(1); - object b = Density.FromKilogramsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2247,21 +2188,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(DensityUnit.Undefined, Density.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(DensityUnit)).Cast(); foreach(var unit in units) { - if (unit == DensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2275,8 +2207,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cg/dl", new Density(1, DensityUnit.CentigramPerDeciliter).ToString()); Assert.Equal("1 cg/L", new Density(1, DensityUnit.CentigramPerLiter).ToString()); @@ -2332,7 +2264,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -2398,10 +2330,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg/m³", new Density(0.123456, DensityUnit.KilogramPerCubicMeter).ToString("s1")); Assert.Equal("0.12 kg/m³", new Density(0.123456, DensityUnit.KilogramPerCubicMeter).ToString("s2")); Assert.Equal("0.123 kg/m³", new Density(0.123456, DensityUnit.KilogramPerCubicMeter).ToString("s3")); @@ -2409,7 +2341,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2423,29 +2355,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg/m³", new Density(0.123456, DensityUnit.KilogramPerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2565,13 +2496,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(QuantityType.Density, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs index e4ed5eab49..f291b1b275 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs @@ -98,12 +98,6 @@ public abstract partial class DurationTestsBase : QuantityTestsBase new object[] { DurationUnit.Year365 }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Duration((double)0.0, DurationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -112,7 +106,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(DurationUnit.Second, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -156,14 +149,9 @@ public void Duration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Duration.Zero, quantityInfo.Zero); Assert.Equal("Duration", quantityInfo.Name); - Assert.Equal(QuantityType.Duration, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {DurationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1747,7 +1735,7 @@ public void ToUnit(DurationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1764,12 +1752,8 @@ public void ToUnit_WithSameUnits_AreEqual(DurationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DurationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Duration.Units.FirstOrDefault(u => u != Duration.BaseUnit && u != DurationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == DurationUnit.Undefined) - fromUnit = Duration.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Duration.Units.Where(u => u != Duration.BaseUnit).DefaultIfEmpty(Duration.BaseUnit).FirstOrDefault(); var quantity = Duration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1855,49 +1839,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => second.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Duration.FromSeconds(1); - var b = Duration.FromSeconds(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Duration.FromSeconds(1); - var b = Duration.FromSeconds(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Duration.FromSeconds(1); - object b = Duration.FromSeconds(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1927,21 +1868,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(second.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(DurationUnit.Undefined, Duration.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(DurationUnit)).Cast(); foreach(var unit in units) { - if (unit == DurationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1955,8 +1887,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 d", new Duration(1, DurationUnit.Day).ToString()); Assert.Equal("1 h", new Duration(1, DurationUnit.Hour).ToString()); @@ -1972,7 +1904,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1998,10 +1930,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 s", new Duration(0.123456, DurationUnit.Second).ToString("s1")); Assert.Equal("0.12 s", new Duration(0.123456, DurationUnit.Second).ToString("s2")); Assert.Equal("0.123 s", new Duration(0.123456, DurationUnit.Second).ToString("s3")); @@ -2009,7 +1941,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2023,29 +1955,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 s", new Duration(0.123456, DurationUnit.Second).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Duration.FromSeconds(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Duration.FromSeconds(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2165,13 +2096,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DurationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(QuantityType.Duration, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs index 1deea57f5d..8947d88e73 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs @@ -94,12 +94,6 @@ public abstract partial class DynamicViscosityTestsBase : QuantityTestsBase new object[] { DynamicViscosityUnit.Reyn }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new DynamicViscosity((double)0.0, DynamicViscosityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -108,7 +102,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -152,14 +145,9 @@ public void DynamicViscosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(DynamicViscosity.Zero, quantityInfo.Zero); Assert.Equal("DynamicViscosity", quantityInfo.Name); - Assert.Equal(QuantityType.DynamicViscosity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {DynamicViscosityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -609,7 +597,7 @@ public void ToUnit(DynamicViscosityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -626,12 +614,8 @@ public void ToUnit_WithSameUnits_AreEqual(DynamicViscosityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DynamicViscosityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = DynamicViscosity.Units.FirstOrDefault(u => u != DynamicViscosity.BaseUnit && u != DynamicViscosityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == DynamicViscosityUnit.Undefined) - fromUnit = DynamicViscosity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = DynamicViscosity.Units.Where(u => u != DynamicViscosity.BaseUnit).DefaultIfEmpty(DynamicViscosity.BaseUnit).FirstOrDefault(); var quantity = DynamicViscosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -716,49 +700,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonsecondpermetersquared.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - var b = DynamicViscosity.FromNewtonSecondsPerMeterSquared(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - var b = DynamicViscosity.FromNewtonSecondsPerMeterSquared(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - object b = DynamicViscosity.FromNewtonSecondsPerMeterSquared(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -788,21 +729,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonsecondpermetersquared.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(DynamicViscosityUnit.Undefined, DynamicViscosity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast(); foreach(var unit in units) { - if (unit == DynamicViscosityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -816,8 +748,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cP", new DynamicViscosity(1, DynamicViscosityUnit.Centipoise).ToString()); Assert.Equal("1 µPa·s", new DynamicViscosity(1, DynamicViscosityUnit.MicropascalSecond).ToString()); @@ -832,7 +764,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -857,10 +789,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Ns/m²", new DynamicViscosity(0.123456, DynamicViscosityUnit.NewtonSecondPerMeterSquared).ToString("s1")); Assert.Equal("0.12 Ns/m²", new DynamicViscosity(0.123456, DynamicViscosityUnit.NewtonSecondPerMeterSquared).ToString("s2")); Assert.Equal("0.123 Ns/m²", new DynamicViscosity(0.123456, DynamicViscosityUnit.NewtonSecondPerMeterSquared).ToString("s3")); @@ -868,7 +800,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -882,29 +814,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Ns/m²", new DynamicViscosity(0.123456, DynamicViscosityUnit.NewtonSecondPerMeterSquared).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1024,13 +955,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DynamicViscosityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(QuantityType.DynamicViscosity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs index 83e64372f2..71b1ebcb70 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class ElectricAdmittanceTestsBase : QuantityTestsBase new object[] { ElectricAdmittanceUnit.Siemens }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricAdmittance((double)0.0, ElectricAdmittanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricAdmittanceUnit.Siemens, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void ElectricAdmittance_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(ElectricAdmittance.Zero, quantityInfo.Zero); Assert.Equal("ElectricAdmittance", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricAdmittance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricAdmittanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(ElectricAdmittanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricAdmittanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricAdmittanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricAdmittance.Units.FirstOrDefault(u => u != ElectricAdmittance.BaseUnit && u != ElectricAdmittanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricAdmittanceUnit.Undefined) - fromUnit = ElectricAdmittance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricAdmittance.Units.Where(u => u != ElectricAdmittance.BaseUnit).DefaultIfEmpty(ElectricAdmittance.BaseUnit).FirstOrDefault(); var quantity = ElectricAdmittance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => siemens.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricAdmittance.FromSiemens(1); - var b = ElectricAdmittance.FromSiemens(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricAdmittance.FromSiemens(1); - var b = ElectricAdmittance.FromSiemens(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricAdmittance.FromSiemens(1); - object b = ElectricAdmittance.FromSiemens(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(siemens.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricAdmittanceUnit.Undefined, ElectricAdmittance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricAdmittanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 µS", new ElectricAdmittance(1, ElectricAdmittanceUnit.Microsiemens).ToString()); Assert.Equal("1 mS", new ElectricAdmittance(1, ElectricAdmittanceUnit.Millisiemens).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 S", new ElectricAdmittance(0.123456, ElectricAdmittanceUnit.Siemens).ToString("s1")); Assert.Equal("0.12 S", new ElectricAdmittance(0.123456, ElectricAdmittanceUnit.Siemens).ToString("s2")); Assert.Equal("0.123 S", new ElectricAdmittance(0.123456, ElectricAdmittanceUnit.Siemens).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 S", new ElectricAdmittance(0.123456, ElectricAdmittanceUnit.Siemens).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricAdmittanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(QuantityType.ElectricAdmittance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs index 6006d21184..a38f00bd96 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class ElectricChargeDensityTestsBase : QuantityTestsBase new object[] { ElectricChargeDensityUnit.CoulombPerCubicMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricChargeDensity((double)0.0, ElectricChargeDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricChargeDensityUnit.CoulombPerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void ElectricChargeDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuan Assert.Equal(ElectricChargeDensity.Zero, quantityInfo.Zero); Assert.Equal("ElectricChargeDensity", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricChargeDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricChargeDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(ElectricChargeDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricChargeDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricChargeDensity.Units.FirstOrDefault(u => u != ElectricChargeDensity.BaseUnit && u != ElectricChargeDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricChargeDensityUnit.Undefined) - fromUnit = ElectricChargeDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricChargeDensity.Units.Where(u => u != ElectricChargeDensity.BaseUnit).DefaultIfEmpty(ElectricChargeDensity.BaseUnit).FirstOrDefault(); var quantity = ElectricChargeDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => coulombpercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - var b = ElectricChargeDensity.FromCoulombsPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - var b = ElectricChargeDensity.FromCoulombsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - object b = ElectricChargeDensity.FromCoulombsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(coulombpercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricChargeDensityUnit.Undefined, ElectricChargeDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricChargeDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 C/m³", new ElectricChargeDensity(1, ElectricChargeDensityUnit.CoulombPerCubicMeter).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 C/m³", new ElectricChargeDensity(0.123456, ElectricChargeDensityUnit.CoulombPerCubicMeter).ToString("s1")); Assert.Equal("0.12 C/m³", new ElectricChargeDensity(0.123456, ElectricChargeDensityUnit.CoulombPerCubicMeter).ToString("s2")); Assert.Equal("0.123 C/m³", new ElectricChargeDensity(0.123456, ElectricChargeDensityUnit.CoulombPerCubicMeter).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 C/m³", new ElectricChargeDensity(0.123456, ElectricChargeDensityUnit.CoulombPerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricChargeDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(QuantityType.ElectricChargeDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs index 6f037b936e..474f50c029 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs @@ -74,12 +74,6 @@ public abstract partial class ElectricChargeTestsBase : QuantityTestsBase new object[] { ElectricChargeUnit.MilliampereHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricCharge((double)0.0, ElectricChargeUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -88,7 +82,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricChargeUnit.Coulomb, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -132,14 +125,9 @@ public void ElectricCharge_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ElectricCharge.Zero, quantityInfo.Zero); Assert.Equal("ElectricCharge", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricCharge, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricChargeUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -419,7 +407,7 @@ public void ToUnit(ElectricChargeUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -436,12 +424,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricChargeUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricCharge.Units.FirstOrDefault(u => u != ElectricCharge.BaseUnit && u != ElectricChargeUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricChargeUnit.Undefined) - fromUnit = ElectricCharge.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricCharge.Units.Where(u => u != ElectricCharge.BaseUnit).DefaultIfEmpty(ElectricCharge.BaseUnit).FirstOrDefault(); var quantity = ElectricCharge.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -521,49 +505,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => coulomb.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricCharge.FromCoulombs(1); - var b = ElectricCharge.FromCoulombs(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricCharge.FromCoulombs(1); - var b = ElectricCharge.FromCoulombs(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricCharge.FromCoulombs(1); - object b = ElectricCharge.FromCoulombs(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -593,21 +534,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(coulomb.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricChargeUnit.Undefined, ElectricCharge.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricChargeUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricChargeUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -621,8 +553,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 A-h", new ElectricCharge(1, ElectricChargeUnit.AmpereHour).ToString()); Assert.Equal("1 C", new ElectricCharge(1, ElectricChargeUnit.Coulomb).ToString()); @@ -632,7 +564,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -652,10 +584,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 C", new ElectricCharge(0.123456, ElectricChargeUnit.Coulomb).ToString("s1")); Assert.Equal("0.12 C", new ElectricCharge(0.123456, ElectricChargeUnit.Coulomb).ToString("s2")); Assert.Equal("0.123 C", new ElectricCharge(0.123456, ElectricChargeUnit.Coulomb).ToString("s3")); @@ -663,7 +595,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -677,29 +609,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 C", new ElectricCharge(0.123456, ElectricChargeUnit.Coulomb).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -819,13 +750,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricChargeUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(QuantityType.ElectricCharge, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs index c651d16775..72edc80f4f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class ElectricConductanceTestsBase : QuantityTestsBase new object[] { ElectricConductanceUnit.Siemens }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricConductance((double)0.0, ElectricConductanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricConductanceUnit.Siemens, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void ElectricConductance_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(ElectricConductance.Zero, quantityInfo.Zero); Assert.Equal("ElectricConductance", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricConductance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricConductanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(ElectricConductanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricConductanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConductanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricConductance.Units.FirstOrDefault(u => u != ElectricConductance.BaseUnit && u != ElectricConductanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricConductanceUnit.Undefined) - fromUnit = ElectricConductance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricConductance.Units.Where(u => u != ElectricConductance.BaseUnit).DefaultIfEmpty(ElectricConductance.BaseUnit).FirstOrDefault(); var quantity = ElectricConductance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => siemens.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricConductance.FromSiemens(1); - var b = ElectricConductance.FromSiemens(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricConductance.FromSiemens(1); - var b = ElectricConductance.FromSiemens(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricConductance.FromSiemens(1); - object b = ElectricConductance.FromSiemens(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(siemens.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricConductanceUnit.Undefined, ElectricConductance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricConductanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 µS", new ElectricConductance(1, ElectricConductanceUnit.Microsiemens).ToString()); Assert.Equal("1 mS", new ElectricConductance(1, ElectricConductanceUnit.Millisiemens).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 S", new ElectricConductance(0.123456, ElectricConductanceUnit.Siemens).ToString("s1")); Assert.Equal("0.12 S", new ElectricConductance(0.123456, ElectricConductanceUnit.Siemens).ToString("s2")); Assert.Equal("0.123 S", new ElectricConductance(0.123456, ElectricConductanceUnit.Siemens).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 S", new ElectricConductance(0.123456, ElectricConductanceUnit.Siemens).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricConductanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(QuantityType.ElectricConductance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs index c4c1f071bb..70337282ef 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class ElectricConductivityTestsBase : QuantityTestsBase new object[] { ElectricConductivityUnit.SiemensPerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricConductivity((double)0.0, ElectricConductivityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricConductivityUnit.SiemensPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void ElectricConductivity_QuantityInfo_ReturnsQuantityInfoDescribingQuant Assert.Equal(ElectricConductivity.Zero, quantityInfo.Zero); Assert.Equal("ElectricConductivity", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricConductivity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricConductivityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -401,7 +389,7 @@ public void ToUnit(ElectricConductivityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -418,12 +406,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricConductivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConductivityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricConductivity.Units.FirstOrDefault(u => u != ElectricConductivity.BaseUnit && u != ElectricConductivityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricConductivityUnit.Undefined) - fromUnit = ElectricConductivity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricConductivity.Units.Where(u => u != ElectricConductivity.BaseUnit).DefaultIfEmpty(ElectricConductivity.BaseUnit).FirstOrDefault(); var quantity = ElectricConductivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -504,49 +488,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => siemenspermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricConductivity.FromSiemensPerMeter(1); - var b = ElectricConductivity.FromSiemensPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricConductivity.FromSiemensPerMeter(1); - var b = ElectricConductivity.FromSiemensPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricConductivity.FromSiemensPerMeter(1); - object b = ElectricConductivity.FromSiemensPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -576,21 +517,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(siemenspermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricConductivityUnit.Undefined, ElectricConductivity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricConductivityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -604,8 +536,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 µS/cm", new ElectricConductivity(1, ElectricConductivityUnit.MicrosiemensPerCentimeter).ToString()); Assert.Equal("1 mS/cm", new ElectricConductivity(1, ElectricConductivityUnit.MillisiemensPerCentimeter).ToString()); @@ -616,7 +548,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -637,10 +569,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 S/m", new ElectricConductivity(0.123456, ElectricConductivityUnit.SiemensPerMeter).ToString("s1")); Assert.Equal("0.12 S/m", new ElectricConductivity(0.123456, ElectricConductivityUnit.SiemensPerMeter).ToString("s2")); Assert.Equal("0.123 S/m", new ElectricConductivity(0.123456, ElectricConductivityUnit.SiemensPerMeter).ToString("s3")); @@ -648,7 +580,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -662,29 +594,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 S/m", new ElectricConductivity(0.123456, ElectricConductivityUnit.SiemensPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -804,13 +735,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricConductivityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(QuantityType.ElectricConductivity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs index 53ce19e87e..f69991cab1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class ElectricCurrentDensityTestsBase : QuantityTestsBas new object[] { ElectricCurrentDensityUnit.AmperePerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricCurrentDensity((double)0.0, ElectricCurrentDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void ElectricCurrentDensity_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(ElectricCurrentDensity.Zero, quantityInfo.Zero); Assert.Equal("ElectricCurrentDensity", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricCurrentDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricCurrentDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(ElectricCurrentDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricCurrentDensity.Units.FirstOrDefault(u => u != ElectricCurrentDensity.BaseUnit && u != ElectricCurrentDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricCurrentDensityUnit.Undefined) - fromUnit = ElectricCurrentDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricCurrentDensity.Units.Where(u => u != ElectricCurrentDensity.BaseUnit).DefaultIfEmpty(ElectricCurrentDensity.BaseUnit).FirstOrDefault(); var quantity = ElectricCurrentDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => amperepersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - var b = ElectricCurrentDensity.FromAmperesPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - var b = ElectricCurrentDensity.FromAmperesPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - object b = ElectricCurrentDensity.FromAmperesPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(amperepersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricCurrentDensityUnit.Undefined, ElectricCurrentDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricCurrentDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 A/ft²", new ElectricCurrentDensity(1, ElectricCurrentDensityUnit.AmperePerSquareFoot).ToString()); Assert.Equal("1 A/in²", new ElectricCurrentDensity(1, ElectricCurrentDensityUnit.AmperePerSquareInch).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 A/m²", new ElectricCurrentDensity(0.123456, ElectricCurrentDensityUnit.AmperePerSquareMeter).ToString("s1")); Assert.Equal("0.12 A/m²", new ElectricCurrentDensity(0.123456, ElectricCurrentDensityUnit.AmperePerSquareMeter).ToString("s2")); Assert.Equal("0.123 A/m²", new ElectricCurrentDensity(0.123456, ElectricCurrentDensityUnit.AmperePerSquareMeter).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 A/m²", new ElectricCurrentDensity(0.123456, ElectricCurrentDensityUnit.AmperePerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCurrentDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(QuantityType.ElectricCurrentDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs index b8c1eb647a..6d79136ba1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class ElectricCurrentGradientTestsBase : QuantityTestsBa new object[] { ElectricCurrentGradientUnit.AmperePerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricCurrentGradient((double)0.0, ElectricCurrentGradientUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricCurrentGradientUnit.AmperePerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void ElectricCurrentGradient_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(ElectricCurrentGradient.Zero, quantityInfo.Zero); Assert.Equal("ElectricCurrentGradient", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricCurrentGradient, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricCurrentGradientUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(ElectricCurrentGradientUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentGradientUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentGradientUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricCurrentGradient.Units.FirstOrDefault(u => u != ElectricCurrentGradient.BaseUnit && u != ElectricCurrentGradientUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricCurrentGradientUnit.Undefined) - fromUnit = ElectricCurrentGradient.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricCurrentGradient.Units.Where(u => u != ElectricCurrentGradient.BaseUnit).DefaultIfEmpty(ElectricCurrentGradient.BaseUnit).FirstOrDefault(); var quantity = ElectricCurrentGradient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => amperepersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricCurrentGradient.FromAmperesPerSecond(1); - var b = ElectricCurrentGradient.FromAmperesPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricCurrentGradient.FromAmperesPerSecond(1); - var b = ElectricCurrentGradient.FromAmperesPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricCurrentGradient.FromAmperesPerSecond(1); - object b = ElectricCurrentGradient.FromAmperesPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(amperepersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricCurrentGradientUnit.Undefined, ElectricCurrentGradient.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricCurrentGradientUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 A/μs", new ElectricCurrentGradient(1, ElectricCurrentGradientUnit.AmperePerMicrosecond).ToString()); Assert.Equal("1 A/ms", new ElectricCurrentGradient(1, ElectricCurrentGradientUnit.AmperePerMillisecond).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 A/s", new ElectricCurrentGradient(0.123456, ElectricCurrentGradientUnit.AmperePerSecond).ToString("s1")); Assert.Equal("0.12 A/s", new ElectricCurrentGradient(0.123456, ElectricCurrentGradientUnit.AmperePerSecond).ToString("s2")); Assert.Equal("0.123 A/s", new ElectricCurrentGradient(0.123456, ElectricCurrentGradientUnit.AmperePerSecond).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 A/s", new ElectricCurrentGradient(0.123456, ElectricCurrentGradientUnit.AmperePerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCurrentGradientUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(QuantityType.ElectricCurrentGradient, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs index 360a731c69..5bfad5942f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs @@ -86,12 +86,6 @@ public abstract partial class ElectricCurrentTestsBase : QuantityTestsBase new object[] { ElectricCurrentUnit.Picoampere }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricCurrent((double)0.0, ElectricCurrentUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -100,7 +94,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricCurrentUnit.Ampere, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -144,14 +137,9 @@ public void ElectricCurrent_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ElectricCurrent.Zero, quantityInfo.Zero); Assert.Equal("ElectricCurrent", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricCurrent, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricCurrentUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -447,7 +435,7 @@ public void ToUnit(ElectricCurrentUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -464,12 +452,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricCurrentUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricCurrent.Units.FirstOrDefault(u => u != ElectricCurrent.BaseUnit && u != ElectricCurrentUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricCurrentUnit.Undefined) - fromUnit = ElectricCurrent.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricCurrent.Units.Where(u => u != ElectricCurrent.BaseUnit).DefaultIfEmpty(ElectricCurrent.BaseUnit).FirstOrDefault(); var quantity = ElectricCurrent.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -552,49 +536,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => ampere.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricCurrent.FromAmperes(1); - var b = ElectricCurrent.FromAmperes(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricCurrent.FromAmperes(1); - var b = ElectricCurrent.FromAmperes(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricCurrent.FromAmperes(1); - object b = ElectricCurrent.FromAmperes(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -624,21 +565,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(ampere.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricCurrentUnit.Undefined, ElectricCurrent.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricCurrentUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -652,8 +584,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 A", new ElectricCurrent(1, ElectricCurrentUnit.Ampere).ToString()); Assert.Equal("1 cA", new ElectricCurrent(1, ElectricCurrentUnit.Centiampere).ToString()); @@ -666,7 +598,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -689,10 +621,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 A", new ElectricCurrent(0.123456, ElectricCurrentUnit.Ampere).ToString("s1")); Assert.Equal("0.12 A", new ElectricCurrent(0.123456, ElectricCurrentUnit.Ampere).ToString("s2")); Assert.Equal("0.123 A", new ElectricCurrent(0.123456, ElectricCurrentUnit.Ampere).ToString("s3")); @@ -700,7 +632,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -714,29 +646,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 A", new ElectricCurrent(0.123456, ElectricCurrentUnit.Ampere).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -856,13 +787,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCurrentUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(QuantityType.ElectricCurrent, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs index a5ecf91710..257b6c8597 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class ElectricFieldTestsBase : QuantityTestsBase new object[] { ElectricFieldUnit.VoltPerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricField((double)0.0, ElectricFieldUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricFieldUnit.VoltPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void ElectricField_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ElectricField.Zero, quantityInfo.Zero); Assert.Equal("ElectricField", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricField, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricFieldUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(ElectricFieldUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricFieldUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricFieldUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricField.Units.FirstOrDefault(u => u != ElectricField.BaseUnit && u != ElectricFieldUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricFieldUnit.Undefined) - fromUnit = ElectricField.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricField.Units.Where(u => u != ElectricField.BaseUnit).DefaultIfEmpty(ElectricField.BaseUnit).FirstOrDefault(); var quantity = ElectricField.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricField.FromVoltsPerMeter(1); - var b = ElectricField.FromVoltsPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricField.FromVoltsPerMeter(1); - var b = ElectricField.FromVoltsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricField.FromVoltsPerMeter(1); - object b = ElectricField.FromVoltsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricFieldUnit.Undefined, ElectricField.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricFieldUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricFieldUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 V/m", new ElectricField(1, ElectricFieldUnit.VoltPerMeter).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 V/m", new ElectricField(0.123456, ElectricFieldUnit.VoltPerMeter).ToString("s1")); Assert.Equal("0.12 V/m", new ElectricField(0.123456, ElectricFieldUnit.VoltPerMeter).ToString("s2")); Assert.Equal("0.123 V/m", new ElectricField(0.123456, ElectricFieldUnit.VoltPerMeter).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 V/m", new ElectricField(0.123456, ElectricFieldUnit.VoltPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricFieldUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(QuantityType.ElectricField, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs index 78a608199c..5b2e5433a3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class ElectricInductanceTestsBase : QuantityTestsBase new object[] { ElectricInductanceUnit.Nanohenry }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricInductance((double)0.0, ElectricInductanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricInductanceUnit.Henry, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void ElectricInductance_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(ElectricInductance.Zero, quantityInfo.Zero); Assert.Equal("ElectricInductance", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricInductance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricInductanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(ElectricInductanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricInductanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricInductanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricInductance.Units.FirstOrDefault(u => u != ElectricInductance.BaseUnit && u != ElectricInductanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricInductanceUnit.Undefined) - fromUnit = ElectricInductance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricInductance.Units.Where(u => u != ElectricInductance.BaseUnit).DefaultIfEmpty(ElectricInductance.BaseUnit).FirstOrDefault(); var quantity = ElectricInductance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => henry.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricInductance.FromHenries(1); - var b = ElectricInductance.FromHenries(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricInductance.FromHenries(1); - var b = ElectricInductance.FromHenries(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricInductance.FromHenries(1); - object b = ElectricInductance.FromHenries(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(henry.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricInductanceUnit.Undefined, ElectricInductance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricInductanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 H", new ElectricInductance(1, ElectricInductanceUnit.Henry).ToString()); Assert.Equal("1 µH", new ElectricInductance(1, ElectricInductanceUnit.Microhenry).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 H", new ElectricInductance(0.123456, ElectricInductanceUnit.Henry).ToString("s1")); Assert.Equal("0.12 H", new ElectricInductance(0.123456, ElectricInductanceUnit.Henry).ToString("s2")); Assert.Equal("0.123 H", new ElectricInductance(0.123456, ElectricInductanceUnit.Henry).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 H", new ElectricInductance(0.123456, ElectricInductanceUnit.Henry).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricInductance.FromHenries(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricInductanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(QuantityType.ElectricInductance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs index 590568e043..35581baee8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialAcTestsBase.g.cs @@ -74,12 +74,6 @@ public abstract partial class ElectricPotentialAcTestsBase : QuantityTestsBase new object[] { ElectricPotentialAcUnit.VoltAc }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricPotentialAc((double)0.0, ElectricPotentialAcUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -88,7 +82,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricPotentialAcUnit.VoltAc, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -132,14 +125,9 @@ public void ElectricPotentialAc_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(ElectricPotentialAc.Zero, quantityInfo.Zero); Assert.Equal("ElectricPotentialAc", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricPotentialAc, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricPotentialAcUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -345,7 +333,7 @@ public void ToUnit(ElectricPotentialAcUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -362,12 +350,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialAcUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialAcUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricPotentialAc.Units.FirstOrDefault(u => u != ElectricPotentialAc.BaseUnit && u != ElectricPotentialAcUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricPotentialAcUnit.Undefined) - fromUnit = ElectricPotentialAc.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricPotentialAc.Units.Where(u => u != ElectricPotentialAc.BaseUnit).DefaultIfEmpty(ElectricPotentialAc.BaseUnit).FirstOrDefault(); var quantity = ElectricPotentialAc.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -447,49 +431,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltac.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricPotentialAc.FromVoltsAc(1); - var b = ElectricPotentialAc.FromVoltsAc(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricPotentialAc.FromVoltsAc(1); - var b = ElectricPotentialAc.FromVoltsAc(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricPotentialAc.FromVoltsAc(1); - object b = ElectricPotentialAc.FromVoltsAc(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -519,21 +460,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltac.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialAcUnit.Undefined, ElectricPotentialAc.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricPotentialAcUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -547,8 +479,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kVac", new ElectricPotentialAc(1, ElectricPotentialAcUnit.KilovoltAc).ToString()); Assert.Equal("1 MVac", new ElectricPotentialAc(1, ElectricPotentialAcUnit.MegavoltAc).ToString()); @@ -558,7 +490,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -578,10 +510,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Vac", new ElectricPotentialAc(0.123456, ElectricPotentialAcUnit.VoltAc).ToString("s1")); Assert.Equal("0.12 Vac", new ElectricPotentialAc(0.123456, ElectricPotentialAcUnit.VoltAc).ToString("s2")); Assert.Equal("0.123 Vac", new ElectricPotentialAc(0.123456, ElectricPotentialAcUnit.VoltAc).ToString("s3")); @@ -589,7 +521,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -603,29 +535,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Vac", new ElectricPotentialAc(0.123456, ElectricPotentialAcUnit.VoltAc).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -745,13 +676,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricPotentialAcUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricPotentialAc.FromVoltsAc(1.0); - Assert.Equal(QuantityType.ElectricPotentialAc, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs index 18cd7c92cd..6b478f6327 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs @@ -134,12 +134,6 @@ public abstract partial class ElectricPotentialChangeRateTestsBase : QuantityTes new object[] { ElectricPotentialChangeRateUnit.VoltPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricPotentialChangeRate((double)0.0, ElectricPotentialChangeRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -148,7 +142,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -192,14 +185,9 @@ public void ElectricPotentialChangeRate_QuantityInfo_ReturnsQuantityInfoDescribi Assert.Equal(ElectricPotentialChangeRate.Zero, quantityInfo.Zero); Assert.Equal("ElectricPotentialChangeRate", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricPotentialChangeRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricPotentialChangeRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -789,7 +777,7 @@ public void ToUnit(ElectricPotentialChangeRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -806,12 +794,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialChangeRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricPotentialChangeRate.Units.FirstOrDefault(u => u != ElectricPotentialChangeRate.BaseUnit && u != ElectricPotentialChangeRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricPotentialChangeRateUnit.Undefined) - fromUnit = ElectricPotentialChangeRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricPotentialChangeRate.Units.Where(u => u != ElectricPotentialChangeRate.BaseUnit).DefaultIfEmpty(ElectricPotentialChangeRate.BaseUnit).FirstOrDefault(); var quantity = ElectricPotentialChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -906,49 +890,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricPotentialChangeRate.FromVoltsPerSeconds(1); - var b = ElectricPotentialChangeRate.FromVoltsPerSeconds(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricPotentialChangeRate.FromVoltsPerSeconds(1); - var b = ElectricPotentialChangeRate.FromVoltsPerSeconds(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricPotentialChangeRate.FromVoltsPerSeconds(1); - object b = ElectricPotentialChangeRate.FromVoltsPerSeconds(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -978,21 +919,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialChangeRateUnit.Undefined, ElectricPotentialChangeRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricPotentialChangeRateUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricPotentialChangeRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1006,8 +938,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kV/h", new ElectricPotentialChangeRate(1, ElectricPotentialChangeRateUnit.KilovoltPerHour).ToString()); Assert.Equal("1 kV/μs", new ElectricPotentialChangeRate(1, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond).ToString()); @@ -1032,7 +964,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1067,10 +999,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 V/s", new ElectricPotentialChangeRate(0.123456, ElectricPotentialChangeRateUnit.VoltPerSecond).ToString("s1")); Assert.Equal("0.12 V/s", new ElectricPotentialChangeRate(0.123456, ElectricPotentialChangeRateUnit.VoltPerSecond).ToString("s2")); Assert.Equal("0.123 V/s", new ElectricPotentialChangeRate(0.123456, ElectricPotentialChangeRateUnit.VoltPerSecond).ToString("s3")); @@ -1078,7 +1010,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1092,29 +1024,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 V/s", new ElectricPotentialChangeRate(0.123456, ElectricPotentialChangeRateUnit.VoltPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1234,13 +1165,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricPotentialChangeRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSeconds(1.0); - Assert.Equal(QuantityType.ElectricPotentialChangeRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs index 355339d866..983699a819 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialDcTestsBase.g.cs @@ -74,12 +74,6 @@ public abstract partial class ElectricPotentialDcTestsBase : QuantityTestsBase new object[] { ElectricPotentialDcUnit.VoltDc }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricPotentialDc((double)0.0, ElectricPotentialDcUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -88,7 +82,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricPotentialDcUnit.VoltDc, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -132,14 +125,9 @@ public void ElectricPotentialDc_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(ElectricPotentialDc.Zero, quantityInfo.Zero); Assert.Equal("ElectricPotentialDc", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricPotentialDc, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricPotentialDcUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -345,7 +333,7 @@ public void ToUnit(ElectricPotentialDcUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -362,12 +350,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialDcUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialDcUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricPotentialDc.Units.FirstOrDefault(u => u != ElectricPotentialDc.BaseUnit && u != ElectricPotentialDcUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricPotentialDcUnit.Undefined) - fromUnit = ElectricPotentialDc.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricPotentialDc.Units.Where(u => u != ElectricPotentialDc.BaseUnit).DefaultIfEmpty(ElectricPotentialDc.BaseUnit).FirstOrDefault(); var quantity = ElectricPotentialDc.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -447,49 +431,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltdc.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricPotentialDc.FromVoltsDc(1); - var b = ElectricPotentialDc.FromVoltsDc(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricPotentialDc.FromVoltsDc(1); - var b = ElectricPotentialDc.FromVoltsDc(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricPotentialDc.FromVoltsDc(1); - object b = ElectricPotentialDc.FromVoltsDc(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -519,21 +460,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltdc.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialDcUnit.Undefined, ElectricPotentialDc.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricPotentialDcUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -547,8 +479,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kVdc", new ElectricPotentialDc(1, ElectricPotentialDcUnit.KilovoltDc).ToString()); Assert.Equal("1 MVdc", new ElectricPotentialDc(1, ElectricPotentialDcUnit.MegavoltDc).ToString()); @@ -558,7 +490,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -578,10 +510,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Vdc", new ElectricPotentialDc(0.123456, ElectricPotentialDcUnit.VoltDc).ToString("s1")); Assert.Equal("0.12 Vdc", new ElectricPotentialDc(0.123456, ElectricPotentialDcUnit.VoltDc).ToString("s2")); Assert.Equal("0.123 Vdc", new ElectricPotentialDc(0.123456, ElectricPotentialDcUnit.VoltDc).ToString("s3")); @@ -589,7 +521,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -603,29 +535,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Vdc", new ElectricPotentialDc(0.123456, ElectricPotentialDcUnit.VoltDc).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -745,13 +676,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricPotentialDcUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricPotentialDc.FromVoltsDc(1.0); - Assert.Equal(QuantityType.ElectricPotentialDc, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs index 168b0ffa3c..09ea4ced3b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs @@ -74,12 +74,6 @@ public abstract partial class ElectricPotentialTestsBase : QuantityTestsBase new object[] { ElectricPotentialUnit.Volt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricPotential((double)0.0, ElectricPotentialUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -88,7 +82,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricPotentialUnit.Volt, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -132,14 +125,9 @@ public void ElectricPotential_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(ElectricPotential.Zero, quantityInfo.Zero); Assert.Equal("ElectricPotential", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricPotential, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricPotentialUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -443,7 +431,7 @@ public void ToUnit(ElectricPotentialUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -460,12 +448,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricPotentialUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentialUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricPotential.Units.FirstOrDefault(u => u != ElectricPotential.BaseUnit && u != ElectricPotentialUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricPotentialUnit.Undefined) - fromUnit = ElectricPotential.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricPotential.Units.Where(u => u != ElectricPotential.BaseUnit).DefaultIfEmpty(ElectricPotential.BaseUnit).FirstOrDefault(); var quantity = ElectricPotential.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -545,49 +529,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => volt.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricPotential.FromVolts(1); - var b = ElectricPotential.FromVolts(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricPotential.FromVolts(1); - var b = ElectricPotential.FromVolts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricPotential.FromVolts(1); - object b = ElectricPotential.FromVolts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -617,21 +558,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(volt.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricPotentialUnit.Undefined, ElectricPotential.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricPotentialUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -645,8 +577,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kV", new ElectricPotential(1, ElectricPotentialUnit.Kilovolt).ToString()); Assert.Equal("1 MV", new ElectricPotential(1, ElectricPotentialUnit.Megavolt).ToString()); @@ -656,7 +588,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -676,10 +608,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 V", new ElectricPotential(0.123456, ElectricPotentialUnit.Volt).ToString("s1")); Assert.Equal("0.12 V", new ElectricPotential(0.123456, ElectricPotentialUnit.Volt).ToString("s2")); Assert.Equal("0.123 V", new ElectricPotential(0.123456, ElectricPotentialUnit.Volt).ToString("s3")); @@ -687,7 +619,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -701,29 +633,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 V", new ElectricPotential(0.123456, ElectricPotentialUnit.Volt).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricPotential.FromVolts(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -843,13 +774,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricPotentialUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(QuantityType.ElectricPotential, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs index 6b72ee52da..e66747226f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class ElectricResistanceTestsBase : QuantityTestsBase new object[] { ElectricResistanceUnit.Ohm }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricResistance((double)0.0, ElectricResistanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricResistanceUnit.Ohm, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void ElectricResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(ElectricResistance.Zero, quantityInfo.Zero); Assert.Equal("ElectricResistance", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricResistance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricResistanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -379,7 +367,7 @@ public void ToUnit(ElectricResistanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -396,12 +384,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricResistanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricResistance.Units.FirstOrDefault(u => u != ElectricResistance.BaseUnit && u != ElectricResistanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricResistanceUnit.Undefined) - fromUnit = ElectricResistance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricResistance.Units.Where(u => u != ElectricResistance.BaseUnit).DefaultIfEmpty(ElectricResistance.BaseUnit).FirstOrDefault(); var quantity = ElectricResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -482,49 +466,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => ohm.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricResistance.FromOhms(1); - var b = ElectricResistance.FromOhms(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricResistance.FromOhms(1); - var b = ElectricResistance.FromOhms(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricResistance.FromOhms(1); - object b = ElectricResistance.FromOhms(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -554,21 +495,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(ohm.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricResistanceUnit.Undefined, ElectricResistance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricResistanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -582,8 +514,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 GΩ", new ElectricResistance(1, ElectricResistanceUnit.Gigaohm).ToString()); Assert.Equal("1 kΩ", new ElectricResistance(1, ElectricResistanceUnit.Kiloohm).ToString()); @@ -594,7 +526,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -615,10 +547,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Ω", new ElectricResistance(0.123456, ElectricResistanceUnit.Ohm).ToString("s1")); Assert.Equal("0.12 Ω", new ElectricResistance(0.123456, ElectricResistanceUnit.Ohm).ToString("s2")); Assert.Equal("0.123 Ω", new ElectricResistance(0.123456, ElectricResistanceUnit.Ohm).ToString("s3")); @@ -626,7 +558,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -640,29 +572,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Ω", new ElectricResistance(0.123456, ElectricResistanceUnit.Ohm).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricResistance.FromOhms(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -782,13 +713,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricResistanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(QuantityType.ElectricResistance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs index 77450703b6..938412a8f7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class ElectricResistivityTestsBase : QuantityTestsBase new object[] { ElectricResistivityUnit.PicoohmMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricResistivity((double)0.0, ElectricResistivityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricResistivityUnit.OhmMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void ElectricResistivity_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(ElectricResistivity.Zero, quantityInfo.Zero); Assert.Equal("ElectricResistivity", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricResistivity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricResistivityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -629,7 +617,7 @@ public void ToUnit(ElectricResistivityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -646,12 +634,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricResistivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistivityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricResistivity.Units.FirstOrDefault(u => u != ElectricResistivity.BaseUnit && u != ElectricResistivityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricResistivityUnit.Undefined) - fromUnit = ElectricResistivity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricResistivity.Units.Where(u => u != ElectricResistivity.BaseUnit).DefaultIfEmpty(ElectricResistivity.BaseUnit).FirstOrDefault(); var quantity = ElectricResistivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -740,49 +724,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => ohmmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricResistivity.FromOhmMeters(1); - var b = ElectricResistivity.FromOhmMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricResistivity.FromOhmMeters(1); - var b = ElectricResistivity.FromOhmMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricResistivity.FromOhmMeters(1); - object b = ElectricResistivity.FromOhmMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -812,21 +753,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(ohmmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricResistivityUnit.Undefined, ElectricResistivity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricResistivityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -840,8 +772,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kΩ·cm", new ElectricResistivity(1, ElectricResistivityUnit.KiloohmCentimeter).ToString()); Assert.Equal("1 kΩ·m", new ElectricResistivity(1, ElectricResistivityUnit.KiloohmMeter).ToString()); @@ -860,7 +792,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -889,10 +821,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Ω·m", new ElectricResistivity(0.123456, ElectricResistivityUnit.OhmMeter).ToString("s1")); Assert.Equal("0.12 Ω·m", new ElectricResistivity(0.123456, ElectricResistivityUnit.OhmMeter).ToString("s2")); Assert.Equal("0.123 Ω·m", new ElectricResistivity(0.123456, ElectricResistivityUnit.OhmMeter).ToString("s3")); @@ -900,7 +832,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -914,29 +846,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Ω·m", new ElectricResistivity(0.123456, ElectricResistivityUnit.OhmMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1056,13 +987,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricResistivityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(QuantityType.ElectricResistivity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs index 81fe8a8a60..00248629f0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class ElectricSurfaceChargeDensityTestsBase : QuantityTe new object[] { ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ElectricSurfaceChargeDensity((double)0.0, ElectricSurfaceChargeDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void ElectricSurfaceChargeDensity_QuantityInfo_ReturnsQuantityInfoDescrib Assert.Equal(ElectricSurfaceChargeDensity.Zero, quantityInfo.Zero); Assert.Equal("ElectricSurfaceChargeDensity", quantityInfo.Name); - Assert.Equal(QuantityType.ElectricSurfaceChargeDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ElectricSurfaceChargeDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(ElectricSurfaceChargeDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(ElectricSurfaceChargeDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricSurfaceChargeDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ElectricSurfaceChargeDensity.Units.FirstOrDefault(u => u != ElectricSurfaceChargeDensity.BaseUnit && u != ElectricSurfaceChargeDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ElectricSurfaceChargeDensityUnit.Undefined) - fromUnit = ElectricSurfaceChargeDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ElectricSurfaceChargeDensity.Units.Where(u => u != ElectricSurfaceChargeDensity.BaseUnit).DefaultIfEmpty(ElectricSurfaceChargeDensity.BaseUnit).FirstOrDefault(); var quantity = ElectricSurfaceChargeDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => coulombpersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - var b = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - var b = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - object b = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(coulombpersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ElectricSurfaceChargeDensityUnit.Undefined, ElectricSurfaceChargeDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ElectricSurfaceChargeDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == ElectricSurfaceChargeDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 C/cm²", new ElectricSurfaceChargeDensity(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter).ToString()); Assert.Equal("1 C/in²", new ElectricSurfaceChargeDensity(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 C/m²", new ElectricSurfaceChargeDensity(0.123456, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter).ToString("s1")); Assert.Equal("0.12 C/m²", new ElectricSurfaceChargeDensity(0.123456, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter).ToString("s2")); Assert.Equal("0.123 C/m²", new ElectricSurfaceChargeDensity(0.123456, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 C/m²", new ElectricSurfaceChargeDensity(0.123456, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricSurfaceChargeDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(QuantityType.ElectricSurfaceChargeDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs index 5e3fc769ef..94ef5323ba 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs @@ -102,12 +102,6 @@ public abstract partial class EnergyDensityTestsBase : QuantityTestsBase new object[] { EnergyDensityUnit.WattHourPerCubicMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new EnergyDensity((double)0.0, EnergyDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -116,7 +110,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(EnergyDensityUnit.JoulePerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -160,14 +153,9 @@ public void EnergyDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(EnergyDensity.Zero, quantityInfo.Zero); Assert.Equal("EnergyDensity", quantityInfo.Name); - Assert.Equal(QuantityType.EnergyDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {EnergyDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -605,7 +593,7 @@ public void ToUnit(EnergyDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -622,12 +610,8 @@ public void ToUnit_WithSameUnits_AreEqual(EnergyDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EnergyDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = EnergyDensity.Units.FirstOrDefault(u => u != EnergyDensity.BaseUnit && u != EnergyDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == EnergyDensityUnit.Undefined) - fromUnit = EnergyDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = EnergyDensity.Units.Where(u => u != EnergyDensity.BaseUnit).DefaultIfEmpty(EnergyDensity.BaseUnit).FirstOrDefault(); var quantity = EnergyDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -714,49 +698,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => joulepercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = EnergyDensity.FromJoulesPerCubicMeter(1); - var b = EnergyDensity.FromJoulesPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = EnergyDensity.FromJoulesPerCubicMeter(1); - var b = EnergyDensity.FromJoulesPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = EnergyDensity.FromJoulesPerCubicMeter(1); - object b = EnergyDensity.FromJoulesPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -786,21 +727,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(joulepercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(EnergyDensityUnit.Undefined, EnergyDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(EnergyDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == EnergyDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -814,8 +746,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 GJ/m³", new EnergyDensity(1, EnergyDensityUnit.GigajoulePerCubicMeter).ToString()); Assert.Equal("1 GWh/m³", new EnergyDensity(1, EnergyDensityUnit.GigawattHourPerCubicMeter).ToString()); @@ -832,7 +764,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -859,10 +791,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/m³", new EnergyDensity(0.123456, EnergyDensityUnit.JoulePerCubicMeter).ToString("s1")); Assert.Equal("0.12 J/m³", new EnergyDensity(0.123456, EnergyDensityUnit.JoulePerCubicMeter).ToString("s2")); Assert.Equal("0.123 J/m³", new EnergyDensity(0.123456, EnergyDensityUnit.JoulePerCubicMeter).ToString("s3")); @@ -870,7 +802,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -884,29 +816,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/m³", new EnergyDensity(0.123456, EnergyDensityUnit.JoulePerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1026,13 +957,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(EnergyDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(QuantityType.EnergyDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs index 2584167b07..273014c23d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs @@ -206,12 +206,6 @@ public abstract partial class EnergyTestsBase : QuantityTestsBase new object[] { EnergyUnit.WattHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Energy((double)0.0, EnergyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -220,7 +214,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(EnergyUnit.Joule, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -264,14 +257,9 @@ public void Energy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Energy.Zero, quantityInfo.Zero); Assert.Equal("Energy", quantityInfo.Name); - Assert.Equal(QuantityType.Energy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {EnergyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1971,7 +1959,7 @@ public void ToUnit(EnergyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1988,12 +1976,8 @@ public void ToUnit_WithSameUnits_AreEqual(EnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EnergyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Energy.Units.FirstOrDefault(u => u != Energy.BaseUnit && u != EnergyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == EnergyUnit.Undefined) - fromUnit = Energy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Energy.Units.Where(u => u != Energy.BaseUnit).DefaultIfEmpty(Energy.BaseUnit).FirstOrDefault(); var quantity = Energy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2106,49 +2090,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => joule.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Energy.FromJoules(1); - var b = Energy.FromJoules(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Energy.FromJoules(1); - var b = Energy.FromJoules(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Energy.FromJoules(1); - object b = Energy.FromJoules(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2178,21 +2119,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(joule.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(EnergyUnit.Undefined, Energy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(EnergyUnit)).Cast(); foreach(var unit in units) { - if (unit == EnergyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2206,8 +2138,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 BTU", new Energy(1, EnergyUnit.BritishThermalUnit).ToString()); Assert.Equal("1 cal", new Energy(1, EnergyUnit.Calorie).ToString()); @@ -2250,7 +2182,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -2303,10 +2235,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J", new Energy(0.123456, EnergyUnit.Joule).ToString("s1")); Assert.Equal("0.12 J", new Energy(0.123456, EnergyUnit.Joule).ToString("s2")); Assert.Equal("0.123 J", new Energy(0.123456, EnergyUnit.Joule).ToString("s3")); @@ -2314,7 +2246,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2328,29 +2260,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J", new Energy(0.123456, EnergyUnit.Joule).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Energy.FromJoules(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Energy.FromJoules(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Energy.FromJoules(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2470,13 +2401,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(EnergyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(QuantityType.Energy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs index 2bcd67842b..6b5fa4022d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs @@ -82,12 +82,6 @@ public abstract partial class EntropyTestsBase : QuantityTestsBase new object[] { EntropyUnit.MegajoulePerKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Entropy((double)0.0, EntropyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -96,7 +90,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(EntropyUnit.JoulePerKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -140,14 +133,9 @@ public void Entropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Entropy.Zero, quantityInfo.Zero); Assert.Equal("Entropy", quantityInfo.Name); - Assert.Equal(QuantityType.Entropy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {EntropyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -435,7 +423,7 @@ public void ToUnit(EntropyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -452,12 +440,8 @@ public void ToUnit_WithSameUnits_AreEqual(EntropyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EntropyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Entropy.Units.FirstOrDefault(u => u != Entropy.BaseUnit && u != EntropyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == EntropyUnit.Undefined) - fromUnit = Entropy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Entropy.Units.Where(u => u != Entropy.BaseUnit).DefaultIfEmpty(Entropy.BaseUnit).FirstOrDefault(); var quantity = Entropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -539,49 +523,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => jouleperkelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Entropy.FromJoulesPerKelvin(1); - var b = Entropy.FromJoulesPerKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Entropy.FromJoulesPerKelvin(1); - var b = Entropy.FromJoulesPerKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Entropy.FromJoulesPerKelvin(1); - object b = Entropy.FromJoulesPerKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -611,21 +552,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(jouleperkelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(EntropyUnit.Undefined, Entropy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(EntropyUnit)).Cast(); foreach(var unit in units) { - if (unit == EntropyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -639,8 +571,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cal/K", new Entropy(1, EntropyUnit.CaloriePerKelvin).ToString()); Assert.Equal("1 J/C", new Entropy(1, EntropyUnit.JoulePerDegreeCelsius).ToString()); @@ -652,7 +584,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -674,10 +606,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/K", new Entropy(0.123456, EntropyUnit.JoulePerKelvin).ToString("s1")); Assert.Equal("0.12 J/K", new Entropy(0.123456, EntropyUnit.JoulePerKelvin).ToString("s2")); Assert.Equal("0.123 J/K", new Entropy(0.123456, EntropyUnit.JoulePerKelvin).ToString("s3")); @@ -685,7 +617,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -699,29 +631,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/K", new Entropy(0.123456, EntropyUnit.JoulePerKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -841,13 +772,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(EntropyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(QuantityType.Entropy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs index 500a73d2e3..342cc970d7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs @@ -114,12 +114,6 @@ public abstract partial class ForceChangeRateTestsBase : QuantityTestsBase new object[] { ForceChangeRateUnit.PoundForcePerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ForceChangeRate((double)0.0, ForceChangeRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -128,7 +122,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ForceChangeRateUnit.NewtonPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -172,14 +165,9 @@ public void ForceChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ForceChangeRate.Zero, quantityInfo.Zero); Assert.Equal("ForceChangeRate", quantityInfo.Name); - Assert.Equal(QuantityType.ForceChangeRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ForceChangeRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -803,7 +791,7 @@ public void ToUnit(ForceChangeRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -820,12 +808,8 @@ public void ToUnit_WithSameUnits_AreEqual(ForceChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceChangeRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ForceChangeRate.Units.FirstOrDefault(u => u != ForceChangeRate.BaseUnit && u != ForceChangeRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ForceChangeRateUnit.Undefined) - fromUnit = ForceChangeRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ForceChangeRate.Units.Where(u => u != ForceChangeRate.BaseUnit).DefaultIfEmpty(ForceChangeRate.BaseUnit).FirstOrDefault(); var quantity = ForceChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -915,49 +899,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ForceChangeRate.FromNewtonsPerSecond(1); - var b = ForceChangeRate.FromNewtonsPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ForceChangeRate.FromNewtonsPerSecond(1); - var b = ForceChangeRate.FromNewtonsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ForceChangeRate.FromNewtonsPerSecond(1); - object b = ForceChangeRate.FromNewtonsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -987,21 +928,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ForceChangeRateUnit.Undefined, ForceChangeRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast(); foreach(var unit in units) { - if (unit == ForceChangeRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1015,8 +947,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cN/s", new ForceChangeRate(1, ForceChangeRateUnit.CentinewtonPerSecond).ToString()); Assert.Equal("1 daN/min", new ForceChangeRate(1, ForceChangeRateUnit.DecanewtonPerMinute).ToString()); @@ -1036,7 +968,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1066,10 +998,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N/s", new ForceChangeRate(0.123456, ForceChangeRateUnit.NewtonPerSecond).ToString("s1")); Assert.Equal("0.12 N/s", new ForceChangeRate(0.123456, ForceChangeRateUnit.NewtonPerSecond).ToString("s2")); Assert.Equal("0.123 N/s", new ForceChangeRate(0.123456, ForceChangeRateUnit.NewtonPerSecond).ToString("s3")); @@ -1077,7 +1009,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1091,29 +1023,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N/s", new ForceChangeRate(0.123456, ForceChangeRateUnit.NewtonPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1233,13 +1164,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ForceChangeRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(QuantityType.ForceChangeRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs index 2ea6e80b9f..af6f2fe038 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs @@ -206,12 +206,6 @@ public abstract partial class ForcePerLengthTestsBase : QuantityTestsBase new object[] { ForcePerLengthUnit.TonneForcePerMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ForcePerLength((double)0.0, ForcePerLengthUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -220,7 +214,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ForcePerLengthUnit.NewtonPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -264,14 +257,9 @@ public void ForcePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ForcePerLength.Zero, quantityInfo.Zero); Assert.Equal("ForcePerLength", quantityInfo.Name); - Assert.Equal(QuantityType.ForcePerLength, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ForcePerLengthUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1663,7 +1651,7 @@ public void ToUnit(ForcePerLengthUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1680,12 +1668,8 @@ public void ToUnit_WithSameUnits_AreEqual(ForcePerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForcePerLengthUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ForcePerLength.Units.FirstOrDefault(u => u != ForcePerLength.BaseUnit && u != ForcePerLengthUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ForcePerLengthUnit.Undefined) - fromUnit = ForcePerLength.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ForcePerLength.Units.Where(u => u != ForcePerLength.BaseUnit).DefaultIfEmpty(ForcePerLength.BaseUnit).FirstOrDefault(); var quantity = ForcePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1798,49 +1782,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ForcePerLength.FromNewtonsPerMeter(1); - var b = ForcePerLength.FromNewtonsPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ForcePerLength.FromNewtonsPerMeter(1); - var b = ForcePerLength.FromNewtonsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ForcePerLength.FromNewtonsPerMeter(1); - object b = ForcePerLength.FromNewtonsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1870,21 +1811,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ForcePerLengthUnit.Undefined, ForcePerLength.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast(); foreach(var unit in units) { - if (unit == ForcePerLengthUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1898,8 +1830,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cN/cm", new ForcePerLength(1, ForcePerLengthUnit.CentinewtonPerCentimeter).ToString()); Assert.Equal("1 cN/m", new ForcePerLength(1, ForcePerLengthUnit.CentinewtonPerMeter).ToString()); @@ -1942,7 +1874,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1995,10 +1927,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N/m", new ForcePerLength(0.123456, ForcePerLengthUnit.NewtonPerMeter).ToString("s1")); Assert.Equal("0.12 N/m", new ForcePerLength(0.123456, ForcePerLengthUnit.NewtonPerMeter).ToString("s2")); Assert.Equal("0.123 N/m", new ForcePerLength(0.123456, ForcePerLengthUnit.NewtonPerMeter).ToString("s3")); @@ -2006,7 +1938,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2020,29 +1952,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N/m", new ForcePerLength(0.123456, ForcePerLengthUnit.NewtonPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2162,13 +2093,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ForcePerLengthUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(QuantityType.ForcePerLength, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs index dcd2b68be7..d80a1384ca 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs @@ -114,12 +114,6 @@ public abstract partial class ForceTestsBase : QuantityTestsBase new object[] { ForceUnit.TonneForce }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Force((double)0.0, ForceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -128,7 +122,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ForceUnit.Newton, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -172,14 +165,9 @@ public void Force_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Force.Zero, quantityInfo.Zero); Assert.Equal("Force", quantityInfo.Name); - Assert.Equal(QuantityType.Force, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ForceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1121,7 +1109,7 @@ public void ToUnit(ForceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1138,12 +1126,8 @@ public void ToUnit_WithSameUnits_AreEqual(ForceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Force.Units.FirstOrDefault(u => u != Force.BaseUnit && u != ForceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ForceUnit.Undefined) - fromUnit = Force.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Force.Units.Where(u => u != Force.BaseUnit).DefaultIfEmpty(Force.BaseUnit).FirstOrDefault(); var quantity = Force.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1233,49 +1217,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newton.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Force.FromNewtons(1); - var b = Force.FromNewtons(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Force.FromNewtons(1); - var b = Force.FromNewtons(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Force.FromNewtons(1); - object b = Force.FromNewtons(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1305,21 +1246,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newton.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ForceUnit.Undefined, Force.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ForceUnit)).Cast(); foreach(var unit in units) { - if (unit == ForceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1333,8 +1265,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 daN", new Force(1, ForceUnit.Decanewton).ToString()); Assert.Equal("1 dyn", new Force(1, ForceUnit.Dyn).ToString()); @@ -1354,7 +1286,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1384,10 +1316,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N", new Force(0.123456, ForceUnit.Newton).ToString("s1")); Assert.Equal("0.12 N", new Force(0.123456, ForceUnit.Newton).ToString("s2")); Assert.Equal("0.123 N", new Force(0.123456, ForceUnit.Newton).ToString("s3")); @@ -1395,7 +1327,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1409,29 +1341,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N", new Force(0.123456, ForceUnit.Newton).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Force.FromNewtons(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Force.FromNewtons(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Force.FromNewtons(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1551,13 +1482,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ForceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(QuantityType.Force, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs index 1529977e81..4d3c5b7a0f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs @@ -98,12 +98,6 @@ public abstract partial class FrequencyTestsBase : QuantityTestsBase new object[] { FrequencyUnit.Terahertz }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Frequency((double)0.0, FrequencyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -112,7 +106,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(FrequencyUnit.Hertz, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -156,14 +149,9 @@ public void Frequency_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Frequency.Zero, quantityInfo.Zero); Assert.Equal("Frequency", quantityInfo.Name); - Assert.Equal(QuantityType.Frequency, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {FrequencyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -739,7 +727,7 @@ public void ToUnit(FrequencyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -756,12 +744,8 @@ public void ToUnit_WithSameUnits_AreEqual(FrequencyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FrequencyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Frequency.Units.FirstOrDefault(u => u != Frequency.BaseUnit && u != FrequencyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == FrequencyUnit.Undefined) - fromUnit = Frequency.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Frequency.Units.Where(u => u != Frequency.BaseUnit).DefaultIfEmpty(Frequency.BaseUnit).FirstOrDefault(); var quantity = Frequency.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -847,49 +831,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => hertz.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Frequency.FromHertz(1); - var b = Frequency.FromHertz(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Frequency.FromHertz(1); - var b = Frequency.FromHertz(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Frequency.FromHertz(1); - object b = Frequency.FromHertz(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -919,21 +860,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(hertz.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(FrequencyUnit.Undefined, Frequency.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(FrequencyUnit)).Cast(); foreach(var unit in units) { - if (unit == FrequencyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -947,8 +879,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 bpm", new Frequency(1, FrequencyUnit.BeatPerMinute).ToString()); Assert.Equal("1 B Units", new Frequency(1, FrequencyUnit.BUnit).ToString()); @@ -964,7 +896,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -990,10 +922,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Hz", new Frequency(0.123456, FrequencyUnit.Hertz).ToString("s1")); Assert.Equal("0.12 Hz", new Frequency(0.123456, FrequencyUnit.Hertz).ToString("s2")); Assert.Equal("0.123 Hz", new Frequency(0.123456, FrequencyUnit.Hertz).ToString("s3")); @@ -1001,7 +933,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1015,29 +947,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Hz", new Frequency(0.123456, FrequencyUnit.Hertz).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Frequency.FromHertz(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Frequency.FromHertz(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1157,13 +1088,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(FrequencyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(QuantityType.Frequency, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs index 29864633e6..53f73c5dd2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class FuelEfficiencyTestsBase : QuantityTestsBase new object[] { FuelEfficiencyUnit.MilePerUsGallon }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new FuelEfficiency((double)0.0, FuelEfficiencyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(FuelEfficiencyUnit.LiterPer100Kilometers, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void FuelEfficiency_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(FuelEfficiency.Zero, quantityInfo.Zero); Assert.Equal("FuelEfficiency", quantityInfo.Name); - Assert.Equal(QuantityType.FuelEfficiency, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {FuelEfficiencyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(FuelEfficiencyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(FuelEfficiencyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FuelEfficiencyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = FuelEfficiency.Units.FirstOrDefault(u => u != FuelEfficiency.BaseUnit && u != FuelEfficiencyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == FuelEfficiencyUnit.Undefined) - fromUnit = FuelEfficiency.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = FuelEfficiency.Units.Where(u => u != FuelEfficiency.BaseUnit).DefaultIfEmpty(FuelEfficiency.BaseUnit).FirstOrDefault(); var quantity = FuelEfficiency.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => literper100kilometers.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = FuelEfficiency.FromLitersPer100Kilometers(1); - var b = FuelEfficiency.FromLitersPer100Kilometers(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = FuelEfficiency.FromLitersPer100Kilometers(1); - var b = FuelEfficiency.FromLitersPer100Kilometers(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = FuelEfficiency.FromLitersPer100Kilometers(1); - object b = FuelEfficiency.FromLitersPer100Kilometers(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(literper100kilometers.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(FuelEfficiencyUnit.Undefined, FuelEfficiency.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast(); foreach(var unit in units) { - if (unit == FuelEfficiencyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 km/L", new FuelEfficiency(1, FuelEfficiencyUnit.KilometerPerLiter).ToString()); Assert.Equal("1 L/100km", new FuelEfficiency(1, FuelEfficiencyUnit.LiterPer100Kilometers).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 L/100km", new FuelEfficiency(0.123456, FuelEfficiencyUnit.LiterPer100Kilometers).ToString("s1")); Assert.Equal("0.12 L/100km", new FuelEfficiency(0.123456, FuelEfficiencyUnit.LiterPer100Kilometers).ToString("s2")); Assert.Equal("0.123 L/100km", new FuelEfficiency(0.123456, FuelEfficiencyUnit.LiterPer100Kilometers).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 L/100km", new FuelEfficiency(0.123456, FuelEfficiencyUnit.LiterPer100Kilometers).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(FuelEfficiencyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = FuelEfficiency.FromLitersPer100Kilometers(1.0); - Assert.Equal(QuantityType.FuelEfficiency, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs index 760ecdd1c8..6ed6def31b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs @@ -126,12 +126,6 @@ public abstract partial class HeatFluxTestsBase : QuantityTestsBase new object[] { HeatFluxUnit.WattPerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new HeatFlux((double)0.0, HeatFluxUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -140,7 +134,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(HeatFluxUnit.WattPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -184,14 +177,9 @@ public void HeatFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(HeatFlux.Zero, quantityInfo.Zero); Assert.Equal("HeatFlux", quantityInfo.Name); - Assert.Equal(QuantityType.HeatFlux, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {HeatFluxUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -833,7 +821,7 @@ public void ToUnit(HeatFluxUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -850,12 +838,8 @@ public void ToUnit_WithSameUnits_AreEqual(HeatFluxUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatFluxUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = HeatFlux.Units.FirstOrDefault(u => u != HeatFlux.BaseUnit && u != HeatFluxUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == HeatFluxUnit.Undefined) - fromUnit = HeatFlux.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = HeatFlux.Units.Where(u => u != HeatFlux.BaseUnit).DefaultIfEmpty(HeatFlux.BaseUnit).FirstOrDefault(); var quantity = HeatFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -948,49 +932,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => wattpersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = HeatFlux.FromWattsPerSquareMeter(1); - var b = HeatFlux.FromWattsPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = HeatFlux.FromWattsPerSquareMeter(1); - var b = HeatFlux.FromWattsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = HeatFlux.FromWattsPerSquareMeter(1); - object b = HeatFlux.FromWattsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1020,21 +961,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(HeatFluxUnit.Undefined, HeatFlux.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(HeatFluxUnit)).Cast(); foreach(var unit in units) { - if (unit == HeatFluxUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1048,8 +980,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 BTU/h·ft²", new HeatFlux(1, HeatFluxUnit.BtuPerHourSquareFoot).ToString()); Assert.Equal("1 BTU/min·ft²", new HeatFlux(1, HeatFluxUnit.BtuPerMinuteSquareFoot).ToString()); @@ -1072,7 +1004,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1105,10 +1037,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W/m²", new HeatFlux(0.123456, HeatFluxUnit.WattPerSquareMeter).ToString("s1")); Assert.Equal("0.12 W/m²", new HeatFlux(0.123456, HeatFluxUnit.WattPerSquareMeter).ToString("s2")); Assert.Equal("0.123 W/m²", new HeatFlux(0.123456, HeatFluxUnit.WattPerSquareMeter).ToString("s3")); @@ -1116,7 +1048,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1130,29 +1062,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W/m²", new HeatFlux(0.123456, HeatFluxUnit.WattPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1272,13 +1203,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(HeatFluxUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(QuantityType.HeatFlux, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs index 29a72861ad..2e7788f787 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class HeatTransferCoefficientTestsBase : QuantityTestsBa new object[] { HeatTransferCoefficientUnit.WattPerSquareMeterKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new HeatTransferCoefficient((double)0.0, HeatTransferCoefficientUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void HeatTransferCoefficient_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(HeatTransferCoefficient.Zero, quantityInfo.Zero); Assert.Equal("HeatTransferCoefficient", quantityInfo.Name); - Assert.Equal(QuantityType.HeatTransferCoefficient, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {HeatTransferCoefficientUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(HeatTransferCoefficientUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(HeatTransferCoefficientUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatTransferCoefficientUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = HeatTransferCoefficient.Units.FirstOrDefault(u => u != HeatTransferCoefficient.BaseUnit && u != HeatTransferCoefficientUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == HeatTransferCoefficientUnit.Undefined) - fromUnit = HeatTransferCoefficient.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = HeatTransferCoefficient.Units.Where(u => u != HeatTransferCoefficient.BaseUnit).DefaultIfEmpty(HeatTransferCoefficient.BaseUnit).FirstOrDefault(); var quantity = HeatTransferCoefficient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => wattpersquaremeterkelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - var b = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - var b = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - object b = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpersquaremeterkelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(HeatTransferCoefficientUnit.Undefined, HeatTransferCoefficient.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast(); foreach(var unit in units) { - if (unit == HeatTransferCoefficientUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 Btu/ft²·hr·°F", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit).ToString()); Assert.Equal("1 W/m²·°C", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s1")); Assert.Equal("0.12 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s2")); Assert.Equal("0.123 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(HeatTransferCoefficientUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(QuantityType.HeatTransferCoefficient, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs index 0e3cd29b0d..34b02d9b53 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class IlluminanceTestsBase : QuantityTestsBase new object[] { IlluminanceUnit.Millilux }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Illuminance((double)0.0, IlluminanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(IlluminanceUnit.Lux, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void Illuminance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Illuminance.Zero, quantityInfo.Zero); Assert.Equal("Illuminance", quantityInfo.Name); - Assert.Equal(QuantityType.Illuminance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {IlluminanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -311,7 +299,7 @@ public void ToUnit(IlluminanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -328,12 +316,8 @@ public void ToUnit_WithSameUnits_AreEqual(IlluminanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IlluminanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Illuminance.Units.FirstOrDefault(u => u != Illuminance.BaseUnit && u != IlluminanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == IlluminanceUnit.Undefined) - fromUnit = Illuminance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Illuminance.Units.Where(u => u != Illuminance.BaseUnit).DefaultIfEmpty(Illuminance.BaseUnit).FirstOrDefault(); var quantity = Illuminance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -412,49 +396,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => lux.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Illuminance.FromLux(1); - var b = Illuminance.FromLux(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Illuminance.FromLux(1); - var b = Illuminance.FromLux(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Illuminance.FromLux(1); - object b = Illuminance.FromLux(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -484,21 +425,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(lux.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(IlluminanceUnit.Undefined, Illuminance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(IlluminanceUnit)).Cast(); foreach(var unit in units) { - if (unit == IlluminanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -512,8 +444,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 klx", new Illuminance(1, IlluminanceUnit.Kilolux).ToString()); Assert.Equal("1 lx", new Illuminance(1, IlluminanceUnit.Lux).ToString()); @@ -522,7 +454,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -541,10 +473,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 lx", new Illuminance(0.123456, IlluminanceUnit.Lux).ToString("s1")); Assert.Equal("0.12 lx", new Illuminance(0.123456, IlluminanceUnit.Lux).ToString("s2")); Assert.Equal("0.123 lx", new Illuminance(0.123456, IlluminanceUnit.Lux).ToString("s3")); @@ -552,7 +484,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -566,29 +498,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 lx", new Illuminance(0.123456, IlluminanceUnit.Lux).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Illuminance.FromLux(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Illuminance.FromLux(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -708,13 +639,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(IlluminanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(QuantityType.Illuminance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs index 5108bec6e0..f542fbfbf6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs @@ -38,63 +38,63 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class InformationTestsBase : QuantityTestsBase { - protected abstract double BitsInOneBit { get; } - protected abstract double BytesInOneBit { get; } - protected abstract double ExabitsInOneBit { get; } - protected abstract double ExabytesInOneBit { get; } - protected abstract double ExbibitsInOneBit { get; } - protected abstract double ExbibytesInOneBit { get; } - protected abstract double GibibitsInOneBit { get; } - protected abstract double GibibytesInOneBit { get; } - protected abstract double GigabitsInOneBit { get; } - protected abstract double GigabytesInOneBit { get; } - protected abstract double KibibitsInOneBit { get; } - protected abstract double KibibytesInOneBit { get; } - protected abstract double KilobitsInOneBit { get; } - protected abstract double KilobytesInOneBit { get; } - protected abstract double MebibitsInOneBit { get; } - protected abstract double MebibytesInOneBit { get; } - protected abstract double MegabitsInOneBit { get; } - protected abstract double MegabytesInOneBit { get; } - protected abstract double PebibitsInOneBit { get; } - protected abstract double PebibytesInOneBit { get; } - protected abstract double PetabitsInOneBit { get; } - protected abstract double PetabytesInOneBit { get; } - protected abstract double TebibitsInOneBit { get; } - protected abstract double TebibytesInOneBit { get; } - protected abstract double TerabitsInOneBit { get; } - protected abstract double TerabytesInOneBit { get; } + protected abstract decimal BitsInOneBit { get; } + protected abstract decimal BytesInOneBit { get; } + protected abstract decimal ExabitsInOneBit { get; } + protected abstract decimal ExabytesInOneBit { get; } + protected abstract decimal ExbibitsInOneBit { get; } + protected abstract decimal ExbibytesInOneBit { get; } + protected abstract decimal GibibitsInOneBit { get; } + protected abstract decimal GibibytesInOneBit { get; } + protected abstract decimal GigabitsInOneBit { get; } + protected abstract decimal GigabytesInOneBit { get; } + protected abstract decimal KibibitsInOneBit { get; } + protected abstract decimal KibibytesInOneBit { get; } + protected abstract decimal KilobitsInOneBit { get; } + protected abstract decimal KilobytesInOneBit { get; } + protected abstract decimal MebibitsInOneBit { get; } + protected abstract decimal MebibytesInOneBit { get; } + protected abstract decimal MegabitsInOneBit { get; } + protected abstract decimal MegabytesInOneBit { get; } + protected abstract decimal PebibitsInOneBit { get; } + protected abstract decimal PebibytesInOneBit { get; } + protected abstract decimal PetabitsInOneBit { get; } + protected abstract decimal PetabytesInOneBit { get; } + protected abstract decimal TebibitsInOneBit { get; } + protected abstract decimal TebibytesInOneBit { get; } + protected abstract decimal TerabitsInOneBit { get; } + protected abstract decimal TerabytesInOneBit { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BitsTolerance { get { return 1e-5; } } - protected virtual double BytesTolerance { get { return 1e-5; } } - protected virtual double ExabitsTolerance { get { return 1e-5; } } - protected virtual double ExabytesTolerance { get { return 1e-5; } } - protected virtual double ExbibitsTolerance { get { return 1e-5; } } - protected virtual double ExbibytesTolerance { get { return 1e-5; } } - protected virtual double GibibitsTolerance { get { return 1e-5; } } - protected virtual double GibibytesTolerance { get { return 1e-5; } } - protected virtual double GigabitsTolerance { get { return 1e-5; } } - protected virtual double GigabytesTolerance { get { return 1e-5; } } - protected virtual double KibibitsTolerance { get { return 1e-5; } } - protected virtual double KibibytesTolerance { get { return 1e-5; } } - protected virtual double KilobitsTolerance { get { return 1e-5; } } - protected virtual double KilobytesTolerance { get { return 1e-5; } } - protected virtual double MebibitsTolerance { get { return 1e-5; } } - protected virtual double MebibytesTolerance { get { return 1e-5; } } - protected virtual double MegabitsTolerance { get { return 1e-5; } } - protected virtual double MegabytesTolerance { get { return 1e-5; } } - protected virtual double PebibitsTolerance { get { return 1e-5; } } - protected virtual double PebibytesTolerance { get { return 1e-5; } } - protected virtual double PetabitsTolerance { get { return 1e-5; } } - protected virtual double PetabytesTolerance { get { return 1e-5; } } - protected virtual double TebibitsTolerance { get { return 1e-5; } } - protected virtual double TebibytesTolerance { get { return 1e-5; } } - protected virtual double TerabitsTolerance { get { return 1e-5; } } - protected virtual double TerabytesTolerance { get { return 1e-5; } } + protected virtual decimal BitsTolerance { get { return 1e-9m; } } + protected virtual decimal BytesTolerance { get { return 1e-9m; } } + protected virtual decimal ExabitsTolerance { get { return 1e-9m; } } + protected virtual decimal ExabytesTolerance { get { return 1e-9m; } } + protected virtual decimal ExbibitsTolerance { get { return 1e-9m; } } + protected virtual decimal ExbibytesTolerance { get { return 1e-9m; } } + protected virtual decimal GibibitsTolerance { get { return 1e-9m; } } + protected virtual decimal GibibytesTolerance { get { return 1e-9m; } } + protected virtual decimal GigabitsTolerance { get { return 1e-9m; } } + protected virtual decimal GigabytesTolerance { get { return 1e-9m; } } + protected virtual decimal KibibitsTolerance { get { return 1e-9m; } } + protected virtual decimal KibibytesTolerance { get { return 1e-9m; } } + protected virtual decimal KilobitsTolerance { get { return 1e-9m; } } + protected virtual decimal KilobytesTolerance { get { return 1e-9m; } } + protected virtual decimal MebibitsTolerance { get { return 1e-9m; } } + protected virtual decimal MebibytesTolerance { get { return 1e-9m; } } + protected virtual decimal MegabitsTolerance { get { return 1e-9m; } } + protected virtual decimal MegabytesTolerance { get { return 1e-9m; } } + protected virtual decimal PebibitsTolerance { get { return 1e-9m; } } + protected virtual decimal PebibytesTolerance { get { return 1e-9m; } } + protected virtual decimal PetabitsTolerance { get { return 1e-9m; } } + protected virtual decimal PetabytesTolerance { get { return 1e-9m; } } + protected virtual decimal TebibitsTolerance { get { return 1e-9m; } } + protected virtual decimal TebibytesTolerance { get { return 1e-9m; } } + protected virtual decimal TerabitsTolerance { get { return 1e-9m; } } + protected virtual decimal TerabytesTolerance { get { return 1e-9m; } } // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(InformationUnit unit) + protected (decimal UnitsInBaseUnit, decimal Tolerence) GetConversionFactor(InformationUnit unit) { return unit switch { @@ -158,12 +158,6 @@ public abstract partial class InformationTestsBase : QuantityTestsBase new object[] { InformationUnit.Terabyte }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Information((decimal)0.0, InformationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -173,7 +167,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(InformationUnit.Bit, quantity.Unit); } - [Fact] public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException() { @@ -204,14 +197,9 @@ public void Information_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Information.Zero, quantityInfo.Zero); Assert.Equal("Information", quantityInfo.Name); - Assert.Equal(QuantityType.Information, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {InformationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -770,7 +758,7 @@ public void ToUnit(InformationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -787,12 +775,8 @@ public void ToUnit_WithSameUnits_AreEqual(InformationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(InformationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Information.Units.FirstOrDefault(u => u != Information.BaseUnit && u != InformationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == InformationUnit.Undefined) - fromUnit = Information.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Information.Units.Where(u => u != Information.BaseUnit).DefaultIfEmpty(Information.BaseUnit).FirstOrDefault(); var quantity = Information.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -893,49 +877,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => bit.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Information.FromBits(1); - var b = Information.FromBits(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Information.FromBits(1); - var b = Information.FromBits(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Information.FromBits(1); - object b = Information.FromBits(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -965,21 +906,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(bit.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(InformationUnit.Undefined, Information.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(InformationUnit)).Cast(); foreach(var unit in units) { - if (unit == InformationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -993,8 +925,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 b", new Information(1, InformationUnit.Bit).ToString()); Assert.Equal("1 B", new Information(1, InformationUnit.Byte).ToString()); @@ -1025,7 +957,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1066,10 +998,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 b", new Information(0.123456m, InformationUnit.Bit).ToString("s1")); Assert.Equal("0.12 b", new Information(0.123456m, InformationUnit.Bit).ToString("s2")); Assert.Equal("0.123 b", new Information(0.123456m, InformationUnit.Bit).ToString("s3")); @@ -1077,7 +1009,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1091,29 +1023,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 b", new Information(0.123456m, InformationUnit.Bit).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Information.FromBits(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Information.FromBits(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Information.FromBits(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1233,13 +1164,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(InformationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(QuantityType.Information, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs index b803d8dd45..153297b39f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class IrradianceTestsBase : QuantityTestsBase new object[] { IrradianceUnit.WattPerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Irradiance((double)0.0, IrradianceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(IrradianceUnit.WattPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void Irradiance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Irradiance.Zero, quantityInfo.Zero); Assert.Equal("Irradiance", quantityInfo.Name); - Assert.Equal(QuantityType.Irradiance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {IrradianceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -629,7 +617,7 @@ public void ToUnit(IrradianceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -646,12 +634,8 @@ public void ToUnit_WithSameUnits_AreEqual(IrradianceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradianceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Irradiance.Units.FirstOrDefault(u => u != Irradiance.BaseUnit && u != IrradianceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == IrradianceUnit.Undefined) - fromUnit = Irradiance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Irradiance.Units.Where(u => u != Irradiance.BaseUnit).DefaultIfEmpty(Irradiance.BaseUnit).FirstOrDefault(); var quantity = Irradiance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -740,49 +724,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => wattpersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Irradiance.FromWattsPerSquareMeter(1); - var b = Irradiance.FromWattsPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Irradiance.FromWattsPerSquareMeter(1); - var b = Irradiance.FromWattsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Irradiance.FromWattsPerSquareMeter(1); - object b = Irradiance.FromWattsPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -812,21 +753,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(IrradianceUnit.Undefined, Irradiance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(IrradianceUnit)).Cast(); foreach(var unit in units) { - if (unit == IrradianceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -840,8 +772,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kW/cm²", new Irradiance(1, IrradianceUnit.KilowattPerSquareCentimeter).ToString()); Assert.Equal("1 kW/m²", new Irradiance(1, IrradianceUnit.KilowattPerSquareMeter).ToString()); @@ -860,7 +792,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -889,10 +821,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W/m²", new Irradiance(0.123456, IrradianceUnit.WattPerSquareMeter).ToString("s1")); Assert.Equal("0.12 W/m²", new Irradiance(0.123456, IrradianceUnit.WattPerSquareMeter).ToString("s2")); Assert.Equal("0.123 W/m²", new Irradiance(0.123456, IrradianceUnit.WattPerSquareMeter).ToString("s3")); @@ -900,7 +832,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -914,29 +846,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W/m²", new Irradiance(0.123456, IrradianceUnit.WattPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1056,13 +987,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(IrradianceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(QuantityType.Irradiance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs index bb364ba99b..723ba69548 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs @@ -82,12 +82,6 @@ public abstract partial class IrradiationTestsBase : QuantityTestsBase new object[] { IrradiationUnit.WattHourPerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Irradiation((double)0.0, IrradiationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -96,7 +90,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(IrradiationUnit.JoulePerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -140,14 +133,9 @@ public void Irradiation_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Irradiation.Zero, quantityInfo.Zero); Assert.Equal("Irradiation", quantityInfo.Name); - Assert.Equal(QuantityType.Irradiation, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {IrradiationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -435,7 +423,7 @@ public void ToUnit(IrradiationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -452,12 +440,8 @@ public void ToUnit_WithSameUnits_AreEqual(IrradiationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradiationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Irradiation.Units.FirstOrDefault(u => u != Irradiation.BaseUnit && u != IrradiationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == IrradiationUnit.Undefined) - fromUnit = Irradiation.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Irradiation.Units.Where(u => u != Irradiation.BaseUnit).DefaultIfEmpty(Irradiation.BaseUnit).FirstOrDefault(); var quantity = Irradiation.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -539,49 +523,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => joulepersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Irradiation.FromJoulesPerSquareMeter(1); - var b = Irradiation.FromJoulesPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Irradiation.FromJoulesPerSquareMeter(1); - var b = Irradiation.FromJoulesPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Irradiation.FromJoulesPerSquareMeter(1); - object b = Irradiation.FromJoulesPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -611,21 +552,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(joulepersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(IrradiationUnit.Undefined, Irradiation.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(IrradiationUnit)).Cast(); foreach(var unit in units) { - if (unit == IrradiationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -639,8 +571,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 J/cm²", new Irradiation(1, IrradiationUnit.JoulePerSquareCentimeter).ToString()); Assert.Equal("1 J/m²", new Irradiation(1, IrradiationUnit.JoulePerSquareMeter).ToString()); @@ -652,7 +584,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -674,10 +606,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/m²", new Irradiation(0.123456, IrradiationUnit.JoulePerSquareMeter).ToString("s1")); Assert.Equal("0.12 J/m²", new Irradiation(0.123456, IrradiationUnit.JoulePerSquareMeter).ToString("s2")); Assert.Equal("0.123 J/m²", new Irradiation(0.123456, IrradiationUnit.JoulePerSquareMeter).ToString("s3")); @@ -685,7 +617,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -699,29 +631,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/m²", new Irradiation(0.123456, IrradiationUnit.JoulePerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -841,13 +772,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(IrradiationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(QuantityType.Irradiation, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs index dc2cc224dd..ea470bde76 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs @@ -98,12 +98,6 @@ public abstract partial class JerkTestsBase : QuantityTestsBase new object[] { JerkUnit.StandardGravitiesPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Jerk((double)0.0, JerkUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -112,7 +106,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(JerkUnit.MeterPerSecondCubed, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -156,14 +149,9 @@ public void Jerk_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Jerk.Zero, quantityInfo.Zero); Assert.Equal("Jerk", quantityInfo.Name); - Assert.Equal(QuantityType.Jerk, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {JerkUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -835,7 +823,7 @@ public void ToUnit(JerkUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -852,12 +840,8 @@ public void ToUnit_WithSameUnits_AreEqual(JerkUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(JerkUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Jerk.Units.FirstOrDefault(u => u != Jerk.BaseUnit && u != JerkUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == JerkUnit.Undefined) - fromUnit = Jerk.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Jerk.Units.Where(u => u != Jerk.BaseUnit).DefaultIfEmpty(Jerk.BaseUnit).FirstOrDefault(); var quantity = Jerk.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -943,49 +927,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => meterpersecondcubed.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Jerk.FromMetersPerSecondCubed(1); - var b = Jerk.FromMetersPerSecondCubed(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Jerk.FromMetersPerSecondCubed(1); - var b = Jerk.FromMetersPerSecondCubed(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Jerk.FromMetersPerSecondCubed(1); - object b = Jerk.FromMetersPerSecondCubed(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1015,21 +956,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(meterpersecondcubed.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(JerkUnit.Undefined, Jerk.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(JerkUnit)).Cast(); foreach(var unit in units) { - if (unit == JerkUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1043,8 +975,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm/s³", new Jerk(1, JerkUnit.CentimeterPerSecondCubed).ToString()); Assert.Equal("1 dm/s³", new Jerk(1, JerkUnit.DecimeterPerSecondCubed).ToString()); @@ -1060,7 +992,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1086,10 +1018,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m/s³", new Jerk(0.123456, JerkUnit.MeterPerSecondCubed).ToString("s1")); Assert.Equal("0.12 m/s³", new Jerk(0.123456, JerkUnit.MeterPerSecondCubed).ToString("s2")); Assert.Equal("0.123 m/s³", new Jerk(0.123456, JerkUnit.MeterPerSecondCubed).ToString("s3")); @@ -1097,7 +1029,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1111,29 +1043,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m/s³", new Jerk(0.123456, JerkUnit.MeterPerSecondCubed).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1253,13 +1184,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(JerkUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(QuantityType.Jerk, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs index ae4297967e..5dfc3f59e8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs @@ -90,12 +90,6 @@ public abstract partial class KinematicViscosityTestsBase : QuantityTestsBase new object[] { KinematicViscosityUnit.Stokes }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new KinematicViscosity((double)0.0, KinematicViscosityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -104,7 +98,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -148,14 +141,9 @@ public void KinematicViscosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(KinematicViscosity.Zero, quantityInfo.Zero); Assert.Equal("KinematicViscosity", quantityInfo.Name); - Assert.Equal(QuantityType.KinematicViscosity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {KinematicViscosityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -695,7 +683,7 @@ public void ToUnit(KinematicViscosityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -712,12 +700,8 @@ public void ToUnit_WithSameUnits_AreEqual(KinematicViscosityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(KinematicViscosityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = KinematicViscosity.Units.FirstOrDefault(u => u != KinematicViscosity.BaseUnit && u != KinematicViscosityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == KinematicViscosityUnit.Undefined) - fromUnit = KinematicViscosity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = KinematicViscosity.Units.Where(u => u != KinematicViscosity.BaseUnit).DefaultIfEmpty(KinematicViscosity.BaseUnit).FirstOrDefault(); var quantity = KinematicViscosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -801,49 +785,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => squaremeterpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = KinematicViscosity.FromSquareMetersPerSecond(1); - var b = KinematicViscosity.FromSquareMetersPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = KinematicViscosity.FromSquareMetersPerSecond(1); - var b = KinematicViscosity.FromSquareMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = KinematicViscosity.FromSquareMetersPerSecond(1); - object b = KinematicViscosity.FromSquareMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -873,21 +814,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(squaremeterpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(KinematicViscosityUnit.Undefined, KinematicViscosity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast(); foreach(var unit in units) { - if (unit == KinematicViscosityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -901,8 +833,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cSt", new KinematicViscosity(1, KinematicViscosityUnit.Centistokes).ToString()); Assert.Equal("1 dSt", new KinematicViscosity(1, KinematicViscosityUnit.Decistokes).ToString()); @@ -916,7 +848,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -940,10 +872,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m²/s", new KinematicViscosity(0.123456, KinematicViscosityUnit.SquareMeterPerSecond).ToString("s1")); Assert.Equal("0.12 m²/s", new KinematicViscosity(0.123456, KinematicViscosityUnit.SquareMeterPerSecond).ToString("s2")); Assert.Equal("0.123 m²/s", new KinematicViscosity(0.123456, KinematicViscosityUnit.SquareMeterPerSecond).ToString("s3")); @@ -951,7 +883,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -965,29 +897,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m²/s", new KinematicViscosity(0.123456, KinematicViscosityUnit.SquareMeterPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1107,13 +1038,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(KinematicViscosityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(QuantityType.KinematicViscosity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs index 7409e1b3e9..2c1936ce6f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LapseRateTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class LapseRateTestsBase : QuantityTestsBase new object[] { LapseRateUnit.DegreeCelsiusPerKilometer }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new LapseRate((double)0.0, LapseRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LapseRateUnit.DegreeCelsiusPerKilometer, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void LapseRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(LapseRate.Zero, quantityInfo.Zero); Assert.Equal("LapseRate", quantityInfo.Name); - Assert.Equal(QuantityType.LapseRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LapseRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(LapseRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(LapseRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LapseRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = LapseRate.Units.FirstOrDefault(u => u != LapseRate.BaseUnit && u != LapseRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LapseRateUnit.Undefined) - fromUnit = LapseRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = LapseRate.Units.Where(u => u != LapseRate.BaseUnit).DefaultIfEmpty(LapseRate.BaseUnit).FirstOrDefault(); var quantity = LapseRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => degreecelsiusperkilometer.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = LapseRate.FromDegreesCelciusPerKilometer(1); - var b = LapseRate.FromDegreesCelciusPerKilometer(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = LapseRate.FromDegreesCelciusPerKilometer(1); - var b = LapseRate.FromDegreesCelciusPerKilometer(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = LapseRate.FromDegreesCelciusPerKilometer(1); - object b = LapseRate.FromDegreesCelciusPerKilometer(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(degreecelsiusperkilometer.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LapseRateUnit.Undefined, LapseRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LapseRateUnit)).Cast(); foreach(var unit in units) { - if (unit == LapseRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 ∆°C/km", new LapseRate(1, LapseRateUnit.DegreeCelsiusPerKilometer).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 ∆°C/km", new LapseRate(0.123456, LapseRateUnit.DegreeCelsiusPerKilometer).ToString("s1")); Assert.Equal("0.12 ∆°C/km", new LapseRate(0.123456, LapseRateUnit.DegreeCelsiusPerKilometer).ToString("s2")); Assert.Equal("0.123 ∆°C/km", new LapseRate(0.123456, LapseRateUnit.DegreeCelsiusPerKilometer).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 ∆°C/km", new LapseRate(0.123456, LapseRateUnit.DegreeCelsiusPerKilometer).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LapseRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = LapseRate.FromDegreesCelciusPerKilometer(1.0); - Assert.Equal(QuantityType.LapseRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs index d9d915314b..8f0d6d1ff1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs @@ -198,12 +198,6 @@ public abstract partial class LengthTestsBase : QuantityTestsBase new object[] { LengthUnit.Yard }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Length((double)0.0, LengthUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -212,7 +206,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LengthUnit.Meter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -256,14 +249,9 @@ public void Length_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Length.Zero, quantityInfo.Zero); Assert.Equal("Length", quantityInfo.Name); - Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LengthUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2225,7 +2213,7 @@ public void ToUnit(LengthUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2242,12 +2230,8 @@ public void ToUnit_WithSameUnits_AreEqual(LengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LengthUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Length.Units.FirstOrDefault(u => u != Length.BaseUnit && u != LengthUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LengthUnit.Undefined) - fromUnit = Length.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Length.Units.Where(u => u != Length.BaseUnit).DefaultIfEmpty(Length.BaseUnit).FirstOrDefault(); var quantity = Length.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2358,49 +2342,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => meter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Length.FromMeters(1); - var b = Length.FromMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Length.FromMeters(1); - var b = Length.FromMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Length.FromMeters(1); - object b = Length.FromMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2430,21 +2371,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(meter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LengthUnit.Undefined, Length.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LengthUnit)).Cast(); foreach(var unit in units) { - if (unit == LengthUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2458,8 +2390,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 Å", new Length(1, LengthUnit.Angstrom).ToString()); Assert.Equal("1 au", new Length(1, LengthUnit.AstronomicalUnit).ToString()); @@ -2500,7 +2432,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -2551,10 +2483,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m", new Length(0.123456, LengthUnit.Meter).ToString("s1")); Assert.Equal("0.12 m", new Length(0.123456, LengthUnit.Meter).ToString("s2")); Assert.Equal("0.123 m", new Length(0.123456, LengthUnit.Meter).ToString("s3")); @@ -2562,7 +2494,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2576,29 +2508,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m", new Length(0.123456, LengthUnit.Meter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Length.FromMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Length.FromMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Length.FromMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2718,13 +2649,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LengthUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(QuantityType.Length, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs index c8c51caf15..266b151a60 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs @@ -62,12 +62,6 @@ public abstract partial class LevelTestsBase : QuantityTestsBase new object[] { LevelUnit.Neper }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Level((double)0.0, LevelUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -76,7 +70,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LevelUnit.Decibel, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -120,14 +113,9 @@ public void Level_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Level.Zero, quantityInfo.Zero); Assert.Equal("Level", quantityInfo.Name); - Assert.Equal(QuantityType.Level, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LevelUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -265,7 +253,7 @@ public void ToUnit(LevelUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -282,12 +270,8 @@ public void ToUnit_WithSameUnits_AreEqual(LevelUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LevelUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Level.Units.FirstOrDefault(u => u != Level.BaseUnit && u != LevelUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LevelUnit.Undefined) - fromUnit = Level.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Level.Units.Where(u => u != Level.BaseUnit).DefaultIfEmpty(Level.BaseUnit).FirstOrDefault(); var quantity = Level.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -368,49 +352,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decibel.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Level.FromDecibels(1); - var b = Level.FromDecibels(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Level.FromDecibels(1); - var b = Level.FromDecibels(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Level.FromDecibels(1); - object b = Level.FromDecibels(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -440,21 +381,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decibel.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LevelUnit.Undefined, Level.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LevelUnit)).Cast(); foreach(var unit in units) { - if (unit == LevelUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -468,15 +400,15 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 dB", new Level(1, LevelUnit.Decibel).ToString()); Assert.Equal("1 Np", new Level(1, LevelUnit.Neper).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -493,10 +425,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 dB", new Level(0.123456, LevelUnit.Decibel).ToString("s1")); Assert.Equal("0.12 dB", new Level(0.123456, LevelUnit.Decibel).ToString("s2")); Assert.Equal("0.123 dB", new Level(0.123456, LevelUnit.Decibel).ToString("s3")); @@ -504,7 +436,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -518,29 +450,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 dB", new Level(0.123456, LevelUnit.Decibel).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Level.FromDecibels(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Level.FromDecibels(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Level.FromDecibels(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -660,13 +591,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LevelUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(QuantityType.Level, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs index c6efe71277..cb1c855bbc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class LinearDensityTestsBase : QuantityTestsBase new object[] { LinearDensityUnit.PoundPerInch }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new LinearDensity((double)0.0, LinearDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LinearDensityUnit.KilogramPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void LinearDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(LinearDensity.Zero, quantityInfo.Zero); Assert.Equal("LinearDensity", quantityInfo.Name); - Assert.Equal(QuantityType.LinearDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LinearDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -673,7 +661,7 @@ public void ToUnit(LinearDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -690,12 +678,8 @@ public void ToUnit_WithSameUnits_AreEqual(LinearDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = LinearDensity.Units.FirstOrDefault(u => u != LinearDensity.BaseUnit && u != LinearDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LinearDensityUnit.Undefined) - fromUnit = LinearDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = LinearDensity.Units.Where(u => u != LinearDensity.BaseUnit).DefaultIfEmpty(LinearDensity.BaseUnit).FirstOrDefault(); var quantity = LinearDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -784,49 +768,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogrampermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = LinearDensity.FromKilogramsPerMeter(1); - var b = LinearDensity.FromKilogramsPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = LinearDensity.FromKilogramsPerMeter(1); - var b = LinearDensity.FromKilogramsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = LinearDensity.FromKilogramsPerMeter(1); - object b = LinearDensity.FromKilogramsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -856,21 +797,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LinearDensityUnit.Undefined, LinearDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LinearDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == LinearDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -884,8 +816,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 g/cm", new LinearDensity(1, LinearDensityUnit.GramPerCentimeter).ToString()); Assert.Equal("1 g/m", new LinearDensity(1, LinearDensityUnit.GramPerMeter).ToString()); @@ -904,7 +836,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -933,10 +865,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg/m", new LinearDensity(0.123456, LinearDensityUnit.KilogramPerMeter).ToString("s1")); Assert.Equal("0.12 kg/m", new LinearDensity(0.123456, LinearDensityUnit.KilogramPerMeter).ToString("s2")); Assert.Equal("0.123 kg/m", new LinearDensity(0.123456, LinearDensityUnit.KilogramPerMeter).ToString("s3")); @@ -944,7 +876,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -958,29 +890,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg/m", new LinearDensity(0.123456, LinearDensityUnit.KilogramPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1100,13 +1031,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LinearDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(QuantityType.LinearDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs index b7bbc0bd3b..0b1cc41464 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs @@ -154,12 +154,6 @@ public abstract partial class LinearPowerDensityTestsBase : QuantityTestsBase new object[] { LinearPowerDensityUnit.WattPerMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new LinearPowerDensity((double)0.0, LinearPowerDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -168,7 +162,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LinearPowerDensityUnit.WattPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -212,14 +205,9 @@ public void LinearPowerDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(LinearPowerDensity.Zero, quantityInfo.Zero); Assert.Equal("LinearPowerDensity", quantityInfo.Name); - Assert.Equal(QuantityType.LinearPowerDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LinearPowerDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -937,7 +925,7 @@ public void ToUnit(LinearPowerDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -954,12 +942,8 @@ public void ToUnit_WithSameUnits_AreEqual(LinearPowerDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearPowerDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = LinearPowerDensity.Units.FirstOrDefault(u => u != LinearPowerDensity.BaseUnit && u != LinearPowerDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LinearPowerDensityUnit.Undefined) - fromUnit = LinearPowerDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = LinearPowerDensity.Units.Where(u => u != LinearPowerDensity.BaseUnit).DefaultIfEmpty(LinearPowerDensity.BaseUnit).FirstOrDefault(); var quantity = LinearPowerDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1059,49 +1043,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => wattpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = LinearPowerDensity.FromWattsPerMeter(1); - var b = LinearPowerDensity.FromWattsPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = LinearPowerDensity.FromWattsPerMeter(1); - var b = LinearPowerDensity.FromWattsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = LinearPowerDensity.FromWattsPerMeter(1); - object b = LinearPowerDensity.FromWattsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1131,21 +1072,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LinearPowerDensityUnit.Undefined, LinearPowerDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LinearPowerDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == LinearPowerDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1159,8 +1091,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 GW/cm", new LinearPowerDensity(1, LinearPowerDensityUnit.GigawattPerCentimeter).ToString()); Assert.Equal("1 GW/ft", new LinearPowerDensity(1, LinearPowerDensityUnit.GigawattPerFoot).ToString()); @@ -1190,7 +1122,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1230,10 +1162,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W/m", new LinearPowerDensity(0.123456, LinearPowerDensityUnit.WattPerMeter).ToString("s1")); Assert.Equal("0.12 W/m", new LinearPowerDensity(0.123456, LinearPowerDensityUnit.WattPerMeter).ToString("s2")); Assert.Equal("0.123 W/m", new LinearPowerDensity(0.123456, LinearPowerDensityUnit.WattPerMeter).ToString("s3")); @@ -1241,7 +1173,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1255,29 +1187,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W/m", new LinearPowerDensity(0.123456, LinearPowerDensityUnit.WattPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1397,13 +1328,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LinearPowerDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(QuantityType.LinearPowerDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs index 07a825ff38..1b8a49e94d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs @@ -94,12 +94,6 @@ public abstract partial class LuminanceTestsBase : QuantityTestsBase new object[] { LuminanceUnit.Nit }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Luminance((double)0.0, LuminanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -108,7 +102,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LuminanceUnit.CandelaPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -152,14 +145,9 @@ public void Luminance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Luminance.Zero, quantityInfo.Zero); Assert.Equal("Luminance", quantityInfo.Name); - Assert.Equal(QuantityType.Luminance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LuminanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -537,7 +525,7 @@ public void ToUnit(LuminanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -554,12 +542,8 @@ public void ToUnit_WithSameUnits_AreEqual(LuminanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Luminance.Units.FirstOrDefault(u => u != Luminance.BaseUnit && u != LuminanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LuminanceUnit.Undefined) - fromUnit = Luminance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Luminance.Units.Where(u => u != Luminance.BaseUnit).DefaultIfEmpty(Luminance.BaseUnit).FirstOrDefault(); var quantity = Luminance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -644,49 +628,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => candelapersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Luminance.FromCandelasPerSquareMeter(1); - var b = Luminance.FromCandelasPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Luminance.FromCandelasPerSquareMeter(1); - var b = Luminance.FromCandelasPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Luminance.FromCandelasPerSquareMeter(1); - object b = Luminance.FromCandelasPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -716,21 +657,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(candelapersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LuminanceUnit.Undefined, Luminance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LuminanceUnit)).Cast(); foreach(var unit in units) { - if (unit == LuminanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -744,8 +676,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 Cd/ft²", new Luminance(1, LuminanceUnit.CandelaPerSquareFoot).ToString()); Assert.Equal("1 Cd/in²", new Luminance(1, LuminanceUnit.CandelaPerSquareInch).ToString()); @@ -760,7 +692,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -785,10 +717,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Cd/m²", new Luminance(0.123456, LuminanceUnit.CandelaPerSquareMeter).ToString("s1")); Assert.Equal("0.12 Cd/m²", new Luminance(0.123456, LuminanceUnit.CandelaPerSquareMeter).ToString("s2")); Assert.Equal("0.123 Cd/m²", new Luminance(0.123456, LuminanceUnit.CandelaPerSquareMeter).ToString("s3")); @@ -796,7 +728,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -810,29 +742,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Cd/m²", new Luminance(0.123456, LuminanceUnit.CandelaPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -952,13 +883,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(QuantityType.Luminance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs index b294177b42..d63f5b9485 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class LuminosityTestsBase : QuantityTestsBase new object[] { LuminosityUnit.Watt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Luminosity((double)0.0, LuminosityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LuminosityUnit.Watt, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void Luminosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Luminosity.Zero, quantityInfo.Zero); Assert.Equal("Luminosity", quantityInfo.Name); - Assert.Equal(QuantityType.Luminosity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LuminosityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -629,7 +617,7 @@ public void ToUnit(LuminosityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -646,12 +634,8 @@ public void ToUnit_WithSameUnits_AreEqual(LuminosityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminosityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Luminosity.Units.FirstOrDefault(u => u != Luminosity.BaseUnit && u != LuminosityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LuminosityUnit.Undefined) - fromUnit = Luminosity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Luminosity.Units.Where(u => u != Luminosity.BaseUnit).DefaultIfEmpty(Luminosity.BaseUnit).FirstOrDefault(); var quantity = Luminosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -740,49 +724,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => watt.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Luminosity.FromWatts(1); - var b = Luminosity.FromWatts(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Luminosity.FromWatts(1); - var b = Luminosity.FromWatts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Luminosity.FromWatts(1); - object b = Luminosity.FromWatts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -812,21 +753,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(watt.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LuminosityUnit.Undefined, Luminosity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LuminosityUnit)).Cast(); foreach(var unit in units) { - if (unit == LuminosityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -840,8 +772,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 daW", new Luminosity(1, LuminosityUnit.Decawatt).ToString()); Assert.Equal("1 dW", new Luminosity(1, LuminosityUnit.Deciwatt).ToString()); @@ -860,7 +792,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -889,10 +821,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W", new Luminosity(0.123456, LuminosityUnit.Watt).ToString("s1")); Assert.Equal("0.12 W", new Luminosity(0.123456, LuminosityUnit.Watt).ToString("s2")); Assert.Equal("0.123 W", new Luminosity(0.123456, LuminosityUnit.Watt).ToString("s3")); @@ -900,7 +832,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -914,29 +846,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W", new Luminosity(0.123456, LuminosityUnit.Watt).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Luminosity.FromWatts(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1056,13 +987,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminosityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(QuantityType.Luminosity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs index a38c789491..d519aeedf9 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class LuminousFluxTestsBase : QuantityTestsBase new object[] { LuminousFluxUnit.Lumen }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new LuminousFlux((double)0.0, LuminousFluxUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LuminousFluxUnit.Lumen, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void LuminousFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(LuminousFlux.Zero, quantityInfo.Zero); Assert.Equal("LuminousFlux", quantityInfo.Name); - Assert.Equal(QuantityType.LuminousFlux, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LuminousFluxUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(LuminousFluxUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(LuminousFluxUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousFluxUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = LuminousFlux.Units.FirstOrDefault(u => u != LuminousFlux.BaseUnit && u != LuminousFluxUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LuminousFluxUnit.Undefined) - fromUnit = LuminousFlux.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = LuminousFlux.Units.Where(u => u != LuminousFlux.BaseUnit).DefaultIfEmpty(LuminousFlux.BaseUnit).FirstOrDefault(); var quantity = LuminousFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => lumen.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = LuminousFlux.FromLumens(1); - var b = LuminousFlux.FromLumens(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = LuminousFlux.FromLumens(1); - var b = LuminousFlux.FromLumens(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = LuminousFlux.FromLumens(1); - object b = LuminousFlux.FromLumens(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(lumen.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LuminousFluxUnit.Undefined, LuminousFlux.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LuminousFluxUnit)).Cast(); foreach(var unit in units) { - if (unit == LuminousFluxUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 lm", new LuminousFlux(1, LuminousFluxUnit.Lumen).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 lm", new LuminousFlux(0.123456, LuminousFluxUnit.Lumen).ToString("s1")); Assert.Equal("0.12 lm", new LuminousFlux(0.123456, LuminousFluxUnit.Lumen).ToString("s2")); Assert.Equal("0.123 lm", new LuminousFlux(0.123456, LuminousFluxUnit.Lumen).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 lm", new LuminousFlux(0.123456, LuminousFluxUnit.Lumen).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = LuminousFlux.FromLumens(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminousFluxUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(QuantityType.LuminousFlux, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs index 0c1af8557e..2fcce36bf3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class LuminousIntensityTestsBase : QuantityTestsBase new object[] { LuminousIntensityUnit.Candela }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new LuminousIntensity((double)0.0, LuminousIntensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(LuminousIntensityUnit.Candela, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void LuminousIntensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(LuminousIntensity.Zero, quantityInfo.Zero); Assert.Equal("LuminousIntensity", quantityInfo.Name); - Assert.Equal(QuantityType.LuminousIntensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {LuminousIntensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(LuminousIntensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(LuminousIntensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousIntensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = LuminousIntensity.Units.FirstOrDefault(u => u != LuminousIntensity.BaseUnit && u != LuminousIntensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == LuminousIntensityUnit.Undefined) - fromUnit = LuminousIntensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = LuminousIntensity.Units.Where(u => u != LuminousIntensity.BaseUnit).DefaultIfEmpty(LuminousIntensity.BaseUnit).FirstOrDefault(); var quantity = LuminousIntensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => candela.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = LuminousIntensity.FromCandela(1); - var b = LuminousIntensity.FromCandela(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = LuminousIntensity.FromCandela(1); - var b = LuminousIntensity.FromCandela(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = LuminousIntensity.FromCandela(1); - object b = LuminousIntensity.FromCandela(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(candela.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(LuminousIntensityUnit.Undefined, LuminousIntensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast(); foreach(var unit in units) { - if (unit == LuminousIntensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cd", new LuminousIntensity(1, LuminousIntensityUnit.Candela).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 cd", new LuminousIntensity(0.123456, LuminousIntensityUnit.Candela).ToString("s1")); Assert.Equal("0.12 cd", new LuminousIntensity(0.123456, LuminousIntensityUnit.Candela).ToString("s2")); Assert.Equal("0.123 cd", new LuminousIntensity(0.123456, LuminousIntensityUnit.Candela).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 cd", new LuminousIntensity(0.123456, LuminousIntensityUnit.Candela).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminousIntensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(QuantityType.LuminousIntensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs index b9f33ea877..80fc5d1717 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class MagneticFieldTestsBase : QuantityTestsBase new object[] { MagneticFieldUnit.Tesla }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MagneticField((double)0.0, MagneticFieldUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MagneticFieldUnit.Tesla, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void MagneticField_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MagneticField.Zero, quantityInfo.Zero); Assert.Equal("MagneticField", quantityInfo.Name); - Assert.Equal(QuantityType.MagneticField, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MagneticFieldUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -401,7 +389,7 @@ public void ToUnit(MagneticFieldUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -418,12 +406,8 @@ public void ToUnit_WithSameUnits_AreEqual(MagneticFieldUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFieldUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MagneticField.Units.FirstOrDefault(u => u != MagneticField.BaseUnit && u != MagneticFieldUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MagneticFieldUnit.Undefined) - fromUnit = MagneticField.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MagneticField.Units.Where(u => u != MagneticField.BaseUnit).DefaultIfEmpty(MagneticField.BaseUnit).FirstOrDefault(); var quantity = MagneticField.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -504,49 +488,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => tesla.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MagneticField.FromTeslas(1); - var b = MagneticField.FromTeslas(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MagneticField.FromTeslas(1); - var b = MagneticField.FromTeslas(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MagneticField.FromTeslas(1); - object b = MagneticField.FromTeslas(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -576,21 +517,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(tesla.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MagneticFieldUnit.Undefined, MagneticField.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MagneticFieldUnit)).Cast(); foreach(var unit in units) { - if (unit == MagneticFieldUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -604,8 +536,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 G", new MagneticField(1, MagneticFieldUnit.Gauss).ToString()); Assert.Equal("1 µT", new MagneticField(1, MagneticFieldUnit.Microtesla).ToString()); @@ -616,7 +548,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -637,10 +569,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 T", new MagneticField(0.123456, MagneticFieldUnit.Tesla).ToString("s1")); Assert.Equal("0.12 T", new MagneticField(0.123456, MagneticFieldUnit.Tesla).ToString("s2")); Assert.Equal("0.123 T", new MagneticField(0.123456, MagneticFieldUnit.Tesla).ToString("s3")); @@ -648,7 +580,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -662,29 +594,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 T", new MagneticField(0.123456, MagneticFieldUnit.Tesla).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MagneticField.FromTeslas(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -804,13 +735,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MagneticFieldUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(QuantityType.MagneticField, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs index 8edd2110dd..6f8165668d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class MagneticFluxTestsBase : QuantityTestsBase new object[] { MagneticFluxUnit.Weber }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MagneticFlux((double)0.0, MagneticFluxUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MagneticFluxUnit.Weber, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void MagneticFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MagneticFlux.Zero, quantityInfo.Zero); Assert.Equal("MagneticFlux", quantityInfo.Name); - Assert.Equal(QuantityType.MagneticFlux, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MagneticFluxUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(MagneticFluxUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(MagneticFluxUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFluxUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MagneticFlux.Units.FirstOrDefault(u => u != MagneticFlux.BaseUnit && u != MagneticFluxUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MagneticFluxUnit.Undefined) - fromUnit = MagneticFlux.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MagneticFlux.Units.Where(u => u != MagneticFlux.BaseUnit).DefaultIfEmpty(MagneticFlux.BaseUnit).FirstOrDefault(); var quantity = MagneticFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => weber.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MagneticFlux.FromWebers(1); - var b = MagneticFlux.FromWebers(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MagneticFlux.FromWebers(1); - var b = MagneticFlux.FromWebers(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MagneticFlux.FromWebers(1); - object b = MagneticFlux.FromWebers(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(weber.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MagneticFluxUnit.Undefined, MagneticFlux.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MagneticFluxUnit)).Cast(); foreach(var unit in units) { - if (unit == MagneticFluxUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 Wb", new MagneticFlux(1, MagneticFluxUnit.Weber).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Wb", new MagneticFlux(0.123456, MagneticFluxUnit.Weber).ToString("s1")); Assert.Equal("0.12 Wb", new MagneticFlux(0.123456, MagneticFluxUnit.Weber).ToString("s2")); Assert.Equal("0.123 Wb", new MagneticFlux(0.123456, MagneticFluxUnit.Weber).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Wb", new MagneticFlux(0.123456, MagneticFluxUnit.Weber).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MagneticFlux.FromWebers(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MagneticFluxUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(QuantityType.MagneticFlux, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs index c377313711..722da50df4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class MagnetizationTestsBase : QuantityTestsBase new object[] { MagnetizationUnit.AmperePerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Magnetization((double)0.0, MagnetizationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MagnetizationUnit.AmperePerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void Magnetization_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Magnetization.Zero, quantityInfo.Zero); Assert.Equal("Magnetization", quantityInfo.Name); - Assert.Equal(QuantityType.Magnetization, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MagnetizationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(MagnetizationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(MagnetizationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagnetizationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Magnetization.Units.FirstOrDefault(u => u != Magnetization.BaseUnit && u != MagnetizationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MagnetizationUnit.Undefined) - fromUnit = Magnetization.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Magnetization.Units.Where(u => u != Magnetization.BaseUnit).DefaultIfEmpty(Magnetization.BaseUnit).FirstOrDefault(); var quantity = Magnetization.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => amperepermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Magnetization.FromAmperesPerMeter(1); - var b = Magnetization.FromAmperesPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Magnetization.FromAmperesPerMeter(1); - var b = Magnetization.FromAmperesPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Magnetization.FromAmperesPerMeter(1); - object b = Magnetization.FromAmperesPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(amperepermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MagnetizationUnit.Undefined, Magnetization.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MagnetizationUnit)).Cast(); foreach(var unit in units) { - if (unit == MagnetizationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 A/m", new Magnetization(1, MagnetizationUnit.AmperePerMeter).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 A/m", new Magnetization(0.123456, MagnetizationUnit.AmperePerMeter).ToString("s1")); Assert.Equal("0.12 A/m", new Magnetization(0.123456, MagnetizationUnit.AmperePerMeter).ToString("s2")); Assert.Equal("0.123 A/m", new Magnetization(0.123456, MagnetizationUnit.AmperePerMeter).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 A/m", new Magnetization(0.123456, MagnetizationUnit.AmperePerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MagnetizationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(QuantityType.Magnetization, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs index e4d60e22ba..e4ef9b7d96 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs @@ -250,12 +250,6 @@ public abstract partial class MassConcentrationTestsBase : QuantityTestsBase new object[] { MassConcentrationUnit.TonnePerCubicMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MassConcentration((double)0.0, MassConcentrationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -264,7 +258,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -308,14 +301,9 @@ public void MassConcentration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(MassConcentration.Zero, quantityInfo.Zero); Assert.Equal("MassConcentration", quantityInfo.Name); - Assert.Equal(QuantityType.MassConcentration, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MassConcentrationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1959,7 +1947,7 @@ public void ToUnit(MassConcentrationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1976,12 +1964,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassConcentrationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassConcentrationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MassConcentration.Units.FirstOrDefault(u => u != MassConcentration.BaseUnit && u != MassConcentrationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MassConcentrationUnit.Undefined) - fromUnit = MassConcentration.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MassConcentration.Units.Where(u => u != MassConcentration.BaseUnit).DefaultIfEmpty(MassConcentration.BaseUnit).FirstOrDefault(); var quantity = MassConcentration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2105,49 +2089,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogrampercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MassConcentration.FromKilogramsPerCubicMeter(1); - var b = MassConcentration.FromKilogramsPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MassConcentration.FromKilogramsPerCubicMeter(1); - var b = MassConcentration.FromKilogramsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MassConcentration.FromKilogramsPerCubicMeter(1); - object b = MassConcentration.FromKilogramsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2177,21 +2118,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassConcentrationUnit.Undefined, MassConcentration.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MassConcentrationUnit)).Cast(); foreach(var unit in units) { - if (unit == MassConcentrationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2205,8 +2137,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cg/dL", new MassConcentration(1, MassConcentrationUnit.CentigramPerDeciliter).ToString()); Assert.Equal("1 cg/L", new MassConcentration(1, MassConcentrationUnit.CentigramPerLiter).ToString()); @@ -2260,7 +2192,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -2324,10 +2256,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg/m³", new MassConcentration(0.123456, MassConcentrationUnit.KilogramPerCubicMeter).ToString("s1")); Assert.Equal("0.12 kg/m³", new MassConcentration(0.123456, MassConcentrationUnit.KilogramPerCubicMeter).ToString("s2")); Assert.Equal("0.123 kg/m³", new MassConcentration(0.123456, MassConcentrationUnit.KilogramPerCubicMeter).ToString("s3")); @@ -2335,7 +2267,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2349,29 +2281,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg/m³", new MassConcentration(0.123456, MassConcentrationUnit.KilogramPerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2491,13 +2422,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassConcentrationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(QuantityType.MassConcentration, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs index 7bf8b8c5e8..914c1455d7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs @@ -186,12 +186,6 @@ public abstract partial class MassFlowTestsBase : QuantityTestsBase new object[] { MassFlowUnit.TonnePerHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MassFlow((double)0.0, MassFlowUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -200,7 +194,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MassFlowUnit.GramPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -244,14 +237,9 @@ public void MassFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MassFlow.Zero, quantityInfo.Zero); Assert.Equal("MassFlow", quantityInfo.Name); - Assert.Equal(QuantityType.MassFlow, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MassFlowUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1561,7 +1549,7 @@ public void ToUnit(MassFlowUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1578,12 +1566,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassFlowUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFlowUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MassFlow.Units.FirstOrDefault(u => u != MassFlow.BaseUnit && u != MassFlowUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MassFlowUnit.Undefined) - fromUnit = MassFlow.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MassFlow.Units.Where(u => u != MassFlow.BaseUnit).DefaultIfEmpty(MassFlow.BaseUnit).FirstOrDefault(); var quantity = MassFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1691,49 +1675,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => grampersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MassFlow.FromGramsPerSecond(1); - var b = MassFlow.FromGramsPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MassFlow.FromGramsPerSecond(1); - var b = MassFlow.FromGramsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MassFlow.FromGramsPerSecond(1); - object b = MassFlow.FromGramsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1763,21 +1704,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(grampersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassFlowUnit.Undefined, MassFlow.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MassFlowUnit)).Cast(); foreach(var unit in units) { - if (unit == MassFlowUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1791,8 +1723,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cg/d", new MassFlow(1, MassFlowUnit.CentigramPerDay).ToString()); Assert.Equal("1 cg/s", new MassFlow(1, MassFlowUnit.CentigramPerSecond).ToString()); @@ -1830,7 +1762,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1878,10 +1810,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 g/s", new MassFlow(0.123456, MassFlowUnit.GramPerSecond).ToString("s1")); Assert.Equal("0.12 g/s", new MassFlow(0.123456, MassFlowUnit.GramPerSecond).ToString("s2")); Assert.Equal("0.123 g/s", new MassFlow(0.123456, MassFlowUnit.GramPerSecond).ToString("s3")); @@ -1889,7 +1821,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1903,29 +1835,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 g/s", new MassFlow(0.123456, MassFlowUnit.GramPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2045,13 +1976,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassFlowUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(QuantityType.MassFlow, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs index b70c99a56c..9a0fe33087 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs @@ -102,12 +102,6 @@ public abstract partial class MassFluxTestsBase : QuantityTestsBase new object[] { MassFluxUnit.KilogramPerSecondPerSquareMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MassFlux((double)0.0, MassFluxUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -116,7 +110,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -160,14 +153,9 @@ public void MassFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MassFlux.Zero, quantityInfo.Zero); Assert.Equal("MassFlux", quantityInfo.Name); - Assert.Equal(QuantityType.MassFlux, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MassFluxUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -605,7 +593,7 @@ public void ToUnit(MassFluxUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -622,12 +610,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassFluxUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFluxUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MassFlux.Units.FirstOrDefault(u => u != MassFlux.BaseUnit && u != MassFluxUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MassFluxUnit.Undefined) - fromUnit = MassFlux.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MassFlux.Units.Where(u => u != MassFlux.BaseUnit).DefaultIfEmpty(MassFlux.BaseUnit).FirstOrDefault(); var quantity = MassFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -714,49 +698,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogrampersecondpersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - var b = MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - var b = MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - object b = MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -786,21 +727,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampersecondpersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassFluxUnit.Undefined, MassFlux.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MassFluxUnit)).Cast(); foreach(var unit in units) { - if (unit == MassFluxUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -814,8 +746,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 g·h⁻¹·cm⁻²", new MassFlux(1, MassFluxUnit.GramPerHourPerSquareCentimeter).ToString()); Assert.Equal("1 g·h⁻¹·m⁻²", new MassFlux(1, MassFluxUnit.GramPerHourPerSquareMeter).ToString()); @@ -832,7 +764,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -859,10 +791,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg·s⁻¹·m⁻²", new MassFlux(0.123456, MassFluxUnit.KilogramPerSecondPerSquareMeter).ToString("s1")); Assert.Equal("0.12 kg·s⁻¹·m⁻²", new MassFlux(0.123456, MassFluxUnit.KilogramPerSecondPerSquareMeter).ToString("s2")); Assert.Equal("0.123 kg·s⁻¹·m⁻²", new MassFlux(0.123456, MassFluxUnit.KilogramPerSecondPerSquareMeter).ToString("s3")); @@ -870,7 +802,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -884,29 +816,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg·s⁻¹·m⁻²", new MassFlux(0.123456, MassFluxUnit.KilogramPerSecondPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1026,13 +957,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassFluxUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(QuantityType.MassFlux, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs index 7b0f67a511..b31feab7c2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs @@ -150,12 +150,6 @@ public abstract partial class MassFractionTestsBase : QuantityTestsBase new object[] { MassFractionUnit.Percent }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MassFraction((double)0.0, MassFractionUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -164,7 +158,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MassFractionUnit.DecimalFraction, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -208,14 +201,9 @@ public void MassFraction_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MassFraction.Zero, quantityInfo.Zero); Assert.Equal("MassFraction", quantityInfo.Name); - Assert.Equal(QuantityType.MassFraction, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MassFractionUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1037,7 +1025,7 @@ public void ToUnit(MassFractionUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1054,12 +1042,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassFractionUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFractionUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MassFraction.Units.FirstOrDefault(u => u != MassFraction.BaseUnit && u != MassFractionUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MassFractionUnit.Undefined) - fromUnit = MassFraction.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MassFraction.Units.Where(u => u != MassFraction.BaseUnit).DefaultIfEmpty(MassFraction.BaseUnit).FirstOrDefault(); var quantity = MassFraction.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1158,49 +1142,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decimalfraction.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MassFraction.FromDecimalFractions(1); - var b = MassFraction.FromDecimalFractions(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MassFraction.FromDecimalFractions(1); - var b = MassFraction.FromDecimalFractions(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MassFraction.FromDecimalFractions(1); - object b = MassFraction.FromDecimalFractions(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1230,21 +1171,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decimalfraction.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassFractionUnit.Undefined, MassFraction.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MassFractionUnit)).Cast(); foreach(var unit in units) { - if (unit == MassFractionUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1258,8 +1190,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cg/g", new MassFraction(1, MassFractionUnit.CentigramPerGram).ToString()); Assert.Equal("1 cg/kg", new MassFraction(1, MassFractionUnit.CentigramPerKilogram).ToString()); @@ -1288,7 +1220,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1327,10 +1259,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1", new MassFraction(0.123456, MassFractionUnit.DecimalFraction).ToString("s1")); Assert.Equal("0.12", new MassFraction(0.123456, MassFractionUnit.DecimalFraction).ToString("s2")); Assert.Equal("0.123", new MassFraction(0.123456, MassFractionUnit.DecimalFraction).ToString("s3")); @@ -1338,7 +1270,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1352,29 +1284,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235", new MassFraction(0.123456, MassFractionUnit.DecimalFraction).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1494,13 +1425,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassFractionUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(QuantityType.MassFraction, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs index bcc49604d5..f7eca52170 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs @@ -166,12 +166,6 @@ public abstract partial class MassMomentOfInertiaTestsBase : QuantityTestsBase new object[] { MassMomentOfInertiaUnit.TonneSquareMilimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MassMomentOfInertia((double)0.0, MassMomentOfInertiaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -180,7 +174,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -224,14 +217,9 @@ public void MassMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(MassMomentOfInertia.Zero, quantityInfo.Zero); Assert.Equal("MassMomentOfInertia", quantityInfo.Name); - Assert.Equal(QuantityType.MassMomentOfInertia, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MassMomentOfInertiaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1149,7 +1137,7 @@ public void ToUnit(MassMomentOfInertiaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1166,12 +1154,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassMomentOfInertiaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassMomentOfInertiaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MassMomentOfInertia.Units.FirstOrDefault(u => u != MassMomentOfInertia.BaseUnit && u != MassMomentOfInertiaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MassMomentOfInertiaUnit.Undefined) - fromUnit = MassMomentOfInertia.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MassMomentOfInertia.Units.Where(u => u != MassMomentOfInertia.BaseUnit).DefaultIfEmpty(MassMomentOfInertia.BaseUnit).FirstOrDefault(); var quantity = MassMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1274,49 +1258,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogramsquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MassMomentOfInertia.FromKilogramSquareMeters(1); - var b = MassMomentOfInertia.FromKilogramSquareMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MassMomentOfInertia.FromKilogramSquareMeters(1); - var b = MassMomentOfInertia.FromKilogramSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MassMomentOfInertia.FromKilogramSquareMeters(1); - object b = MassMomentOfInertia.FromKilogramSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1346,21 +1287,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogramsquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassMomentOfInertiaUnit.Undefined, MassMomentOfInertia.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast(); foreach(var unit in units) { - if (unit == MassMomentOfInertiaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1374,8 +1306,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 g·cm²", new MassMomentOfInertia(1, MassMomentOfInertiaUnit.GramSquareCentimeter).ToString()); Assert.Equal("1 g·dm²", new MassMomentOfInertia(1, MassMomentOfInertiaUnit.GramSquareDecimeter).ToString()); @@ -1408,7 +1340,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1451,10 +1383,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg·m²", new MassMomentOfInertia(0.123456, MassMomentOfInertiaUnit.KilogramSquareMeter).ToString("s1")); Assert.Equal("0.12 kg·m²", new MassMomentOfInertia(0.123456, MassMomentOfInertiaUnit.KilogramSquareMeter).ToString("s2")); Assert.Equal("0.123 kg·m²", new MassMomentOfInertia(0.123456, MassMomentOfInertiaUnit.KilogramSquareMeter).ToString("s3")); @@ -1462,7 +1394,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1476,29 +1408,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg·m²", new MassMomentOfInertia(0.123456, MassMomentOfInertiaUnit.KilogramSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1618,13 +1549,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassMomentOfInertiaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(QuantityType.MassMomentOfInertia, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs index e38f08e9a9..2b150d1fe1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs @@ -154,12 +154,6 @@ public abstract partial class MassTestsBase : QuantityTestsBase new object[] { MassUnit.Tonne }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Mass((double)0.0, MassUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -168,7 +162,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MassUnit.Kilogram, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -212,14 +205,9 @@ public void Mass_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Mass.Zero, quantityInfo.Zero); Assert.Equal("Mass", quantityInfo.Name); - Assert.Equal(QuantityType.Mass, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MassUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2059,7 +2047,7 @@ public void ToUnit(MassUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2076,12 +2064,8 @@ public void ToUnit_WithSameUnits_AreEqual(MassUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Mass.Units.FirstOrDefault(u => u != Mass.BaseUnit && u != MassUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MassUnit.Undefined) - fromUnit = Mass.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Mass.Units.Where(u => u != Mass.BaseUnit).DefaultIfEmpty(Mass.BaseUnit).FirstOrDefault(); var quantity = Mass.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2181,49 +2165,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogram.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Mass.FromKilograms(1); - var b = Mass.FromKilograms(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Mass.FromKilograms(1); - var b = Mass.FromKilograms(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Mass.FromKilograms(1); - object b = Mass.FromKilograms(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2253,21 +2194,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogram.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MassUnit.Undefined, Mass.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MassUnit)).Cast(); foreach(var unit in units) { - if (unit == MassUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2281,8 +2213,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cg", new Mass(1, MassUnit.Centigram).ToString()); Assert.Equal("1 dag", new Mass(1, MassUnit.Decagram).ToString()); @@ -2312,7 +2244,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -2352,10 +2284,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg", new Mass(0.123456, MassUnit.Kilogram).ToString("s1")); Assert.Equal("0.12 kg", new Mass(0.123456, MassUnit.Kilogram).ToString("s2")); Assert.Equal("0.123 kg", new Mass(0.123456, MassUnit.Kilogram).ToString("s3")); @@ -2363,7 +2295,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2377,29 +2309,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg", new Mass(0.123456, MassUnit.Kilogram).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Mass.FromKilograms(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Mass.FromKilograms(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2519,13 +2450,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(QuantityType.Mass, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs index 1f7c08cedd..6f25873f55 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class MolarEnergyTestsBase : QuantityTestsBase new object[] { MolarEnergyUnit.MegajoulePerMole }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MolarEnergy((double)0.0, MolarEnergyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MolarEnergyUnit.JoulePerMole, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void MolarEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MolarEnergy.Zero, quantityInfo.Zero); Assert.Equal("MolarEnergy", quantityInfo.Name); - Assert.Equal(QuantityType.MolarEnergy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MolarEnergyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(MolarEnergyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEnergyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MolarEnergy.Units.FirstOrDefault(u => u != MolarEnergy.BaseUnit && u != MolarEnergyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MolarEnergyUnit.Undefined) - fromUnit = MolarEnergy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MolarEnergy.Units.Where(u => u != MolarEnergy.BaseUnit).DefaultIfEmpty(MolarEnergy.BaseUnit).FirstOrDefault(); var quantity = MolarEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => joulepermole.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MolarEnergy.FromJoulesPerMole(1); - var b = MolarEnergy.FromJoulesPerMole(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MolarEnergy.FromJoulesPerMole(1); - var b = MolarEnergy.FromJoulesPerMole(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MolarEnergy.FromJoulesPerMole(1); - object b = MolarEnergy.FromJoulesPerMole(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(joulepermole.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarEnergyUnit.Undefined, MolarEnergy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MolarEnergyUnit)).Cast(); foreach(var unit in units) { - if (unit == MolarEnergyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 J/mol", new MolarEnergy(1, MolarEnergyUnit.JoulePerMole).ToString()); Assert.Equal("1 kJ/mol", new MolarEnergy(1, MolarEnergyUnit.KilojoulePerMole).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/mol", new MolarEnergy(0.123456, MolarEnergyUnit.JoulePerMole).ToString("s1")); Assert.Equal("0.12 J/mol", new MolarEnergy(0.123456, MolarEnergyUnit.JoulePerMole).ToString("s2")); Assert.Equal("0.123 J/mol", new MolarEnergy(0.123456, MolarEnergyUnit.JoulePerMole).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/mol", new MolarEnergy(0.123456, MolarEnergyUnit.JoulePerMole).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarEnergyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(QuantityType.MolarEnergy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs index 692b5631c8..c00f2bf481 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class MolarEntropyTestsBase : QuantityTestsBase new object[] { MolarEntropyUnit.MegajoulePerMoleKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MolarEntropy((double)0.0, MolarEntropyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MolarEntropyUnit.JoulePerMoleKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void MolarEntropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MolarEntropy.Zero, quantityInfo.Zero); Assert.Equal("MolarEntropy", quantityInfo.Name); - Assert.Equal(QuantityType.MolarEntropy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MolarEntropyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(MolarEntropyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarEntropyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEntropyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MolarEntropy.Units.FirstOrDefault(u => u != MolarEntropy.BaseUnit && u != MolarEntropyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MolarEntropyUnit.Undefined) - fromUnit = MolarEntropy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MolarEntropy.Units.Where(u => u != MolarEntropy.BaseUnit).DefaultIfEmpty(MolarEntropy.BaseUnit).FirstOrDefault(); var quantity = MolarEntropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => joulepermolekelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MolarEntropy.FromJoulesPerMoleKelvin(1); - var b = MolarEntropy.FromJoulesPerMoleKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MolarEntropy.FromJoulesPerMoleKelvin(1); - var b = MolarEntropy.FromJoulesPerMoleKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MolarEntropy.FromJoulesPerMoleKelvin(1); - object b = MolarEntropy.FromJoulesPerMoleKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(joulepermolekelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarEntropyUnit.Undefined, MolarEntropy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MolarEntropyUnit)).Cast(); foreach(var unit in units) { - if (unit == MolarEntropyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 J/(mol*K)", new MolarEntropy(1, MolarEntropyUnit.JoulePerMoleKelvin).ToString()); Assert.Equal("1 kJ/(mol*K)", new MolarEntropy(1, MolarEntropyUnit.KilojoulePerMoleKelvin).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/(mol*K)", new MolarEntropy(0.123456, MolarEntropyUnit.JoulePerMoleKelvin).ToString("s1")); Assert.Equal("0.12 J/(mol*K)", new MolarEntropy(0.123456, MolarEntropyUnit.JoulePerMoleKelvin).ToString("s2")); Assert.Equal("0.123 J/(mol*K)", new MolarEntropy(0.123456, MolarEntropyUnit.JoulePerMoleKelvin).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/(mol*K)", new MolarEntropy(0.123456, MolarEntropyUnit.JoulePerMoleKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarEntropyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(QuantityType.MolarEntropy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs index 6ed3d868d5..4db223d70a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs @@ -102,12 +102,6 @@ public abstract partial class MolarMassTestsBase : QuantityTestsBase new object[] { MolarMassUnit.PoundPerMole }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new MolarMass((double)0.0, MolarMassUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -116,7 +110,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MolarMassUnit.KilogramPerMole, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -160,14 +153,9 @@ public void MolarMass_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(MolarMass.Zero, quantityInfo.Zero); Assert.Equal("MolarMass", quantityInfo.Name); - Assert.Equal(QuantityType.MolarMass, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MolarMassUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -893,7 +881,7 @@ public void ToUnit(MolarMassUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -910,12 +898,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarMassUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarMassUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = MolarMass.Units.FirstOrDefault(u => u != MolarMass.BaseUnit && u != MolarMassUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MolarMassUnit.Undefined) - fromUnit = MolarMass.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = MolarMass.Units.Where(u => u != MolarMass.BaseUnit).DefaultIfEmpty(MolarMass.BaseUnit).FirstOrDefault(); var quantity = MolarMass.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1002,49 +986,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kilogrampermole.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = MolarMass.FromKilogramsPerMole(1); - var b = MolarMass.FromKilogramsPerMole(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = MolarMass.FromKilogramsPerMole(1); - var b = MolarMass.FromKilogramsPerMole(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = MolarMass.FromKilogramsPerMole(1); - object b = MolarMass.FromKilogramsPerMole(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1074,21 +1015,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampermole.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarMassUnit.Undefined, MolarMass.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MolarMassUnit)).Cast(); foreach(var unit in units) { - if (unit == MolarMassUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1102,8 +1034,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cg/mol", new MolarMass(1, MolarMassUnit.CentigramPerMole).ToString()); Assert.Equal("1 dag/mol", new MolarMass(1, MolarMassUnit.DecagramPerMole).ToString()); @@ -1120,7 +1052,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1147,10 +1079,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 kg/mol", new MolarMass(0.123456, MolarMassUnit.KilogramPerMole).ToString("s1")); Assert.Equal("0.12 kg/mol", new MolarMass(0.123456, MolarMassUnit.KilogramPerMole).ToString("s2")); Assert.Equal("0.123 kg/mol", new MolarMass(0.123456, MolarMassUnit.KilogramPerMole).ToString("s3")); @@ -1158,7 +1090,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1172,29 +1104,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 kg/mol", new MolarMass(0.123456, MolarMassUnit.KilogramPerMole).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1314,13 +1245,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarMassUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(QuantityType.MolarMass, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs index 2215fb3ec8..235cf2cf80 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs @@ -106,12 +106,6 @@ public abstract partial class MolarityTestsBase : QuantityTestsBase new object[] { MolarityUnit.PicomolesPerLiter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Molarity((double)0.0, MolarityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -120,7 +114,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(MolarityUnit.MolesPerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -164,14 +157,9 @@ public void Molarity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Molarity.Zero, quantityInfo.Zero); Assert.Equal("Molarity", quantityInfo.Name); - Assert.Equal(QuantityType.Molarity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {MolarityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -594,7 +582,7 @@ public void ToUnit(MolarityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -611,12 +599,8 @@ public void ToUnit_WithSameUnits_AreEqual(MolarityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Molarity.Units.FirstOrDefault(u => u != Molarity.BaseUnit && u != MolarityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == MolarityUnit.Undefined) - fromUnit = Molarity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Molarity.Units.Where(u => u != Molarity.BaseUnit).DefaultIfEmpty(Molarity.BaseUnit).FirstOrDefault(); var quantity = Molarity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -708,49 +692,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => molespercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Molarity.FromMolesPerCubicMeter(1); - var b = Molarity.FromMolesPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Molarity.FromMolesPerCubicMeter(1); - var b = Molarity.FromMolesPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Molarity.FromMolesPerCubicMeter(1); - object b = Molarity.FromMolesPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -780,21 +721,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(molespercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(MolarityUnit.Undefined, Molarity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(MolarityUnit)).Cast(); foreach(var unit in units) { - if (unit == MolarityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -808,8 +740,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cmol/L", new Molarity(1, MolarityUnit.CentimolePerLiter).ToString()); Assert.Equal("1 cmol/L", new Molarity(1, MolarityUnit.CentimolesPerLiter).ToString()); @@ -831,7 +763,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -863,10 +795,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 mol/m³", new Molarity(0.123456, MolarityUnit.MolesPerCubicMeter).ToString("s1")); Assert.Equal("0.12 mol/m³", new Molarity(0.123456, MolarityUnit.MolesPerCubicMeter).ToString("s2")); Assert.Equal("0.123 mol/m³", new Molarity(0.123456, MolarityUnit.MolesPerCubicMeter).ToString("s3")); @@ -874,7 +806,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -888,29 +820,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 mol/m³", new Molarity(0.123456, MolarityUnit.MolesPerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1030,13 +961,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(QuantityType.Molarity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs index 75c50bbb1e..3ab8fbe7fc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class PermeabilityTestsBase : QuantityTestsBase new object[] { PermeabilityUnit.HenryPerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Permeability((double)0.0, PermeabilityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PermeabilityUnit.HenryPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void Permeability_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Permeability.Zero, quantityInfo.Zero); Assert.Equal("Permeability", quantityInfo.Name); - Assert.Equal(QuantityType.Permeability, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PermeabilityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(PermeabilityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(PermeabilityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermeabilityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Permeability.Units.FirstOrDefault(u => u != Permeability.BaseUnit && u != PermeabilityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PermeabilityUnit.Undefined) - fromUnit = Permeability.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Permeability.Units.Where(u => u != Permeability.BaseUnit).DefaultIfEmpty(Permeability.BaseUnit).FirstOrDefault(); var quantity = Permeability.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => henrypermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Permeability.FromHenriesPerMeter(1); - var b = Permeability.FromHenriesPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Permeability.FromHenriesPerMeter(1); - var b = Permeability.FromHenriesPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Permeability.FromHenriesPerMeter(1); - object b = Permeability.FromHenriesPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(henrypermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PermeabilityUnit.Undefined, Permeability.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PermeabilityUnit)).Cast(); foreach(var unit in units) { - if (unit == PermeabilityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 H/m", new Permeability(1, PermeabilityUnit.HenryPerMeter).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 H/m", new Permeability(0.123456, PermeabilityUnit.HenryPerMeter).ToString("s1")); Assert.Equal("0.12 H/m", new Permeability(0.123456, PermeabilityUnit.HenryPerMeter).ToString("s2")); Assert.Equal("0.123 H/m", new Permeability(0.123456, PermeabilityUnit.HenryPerMeter).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 H/m", new Permeability(0.123456, PermeabilityUnit.HenryPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PermeabilityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(QuantityType.Permeability, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs index 0ce2fc21c1..4f794cfad2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class PermittivityTestsBase : QuantityTestsBase new object[] { PermittivityUnit.FaradPerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Permittivity((double)0.0, PermittivityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PermittivityUnit.FaradPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void Permittivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Permittivity.Zero, quantityInfo.Zero); Assert.Equal("Permittivity", quantityInfo.Name); - Assert.Equal(QuantityType.Permittivity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PermittivityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(PermittivityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(PermittivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermittivityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Permittivity.Units.FirstOrDefault(u => u != Permittivity.BaseUnit && u != PermittivityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PermittivityUnit.Undefined) - fromUnit = Permittivity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Permittivity.Units.Where(u => u != Permittivity.BaseUnit).DefaultIfEmpty(Permittivity.BaseUnit).FirstOrDefault(); var quantity = Permittivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => faradpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Permittivity.FromFaradsPerMeter(1); - var b = Permittivity.FromFaradsPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Permittivity.FromFaradsPerMeter(1); - var b = Permittivity.FromFaradsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Permittivity.FromFaradsPerMeter(1); - object b = Permittivity.FromFaradsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(faradpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PermittivityUnit.Undefined, Permittivity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PermittivityUnit)).Cast(); foreach(var unit in units) { - if (unit == PermittivityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 F/m", new Permittivity(1, PermittivityUnit.FaradPerMeter).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 F/m", new Permittivity(0.123456, PermittivityUnit.FaradPerMeter).ToString("s1")); Assert.Equal("0.12 F/m", new Permittivity(0.123456, PermittivityUnit.FaradPerMeter).ToString("s2")); Assert.Equal("0.123 F/m", new Permittivity(0.123456, PermittivityUnit.FaradPerMeter).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 F/m", new Permittivity(0.123456, PermittivityUnit.FaradPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PermittivityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(QuantityType.Permittivity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs index 09fe2125b7..fe3df200e7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs @@ -74,12 +74,6 @@ public abstract partial class PorousMediumPermeabilityTestsBase : QuantityTestsB new object[] { PorousMediumPermeabilityUnit.SquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new PorousMediumPermeability((double)0.0, PorousMediumPermeabilityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -88,7 +82,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PorousMediumPermeabilityUnit.SquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -132,14 +125,9 @@ public void PorousMediumPermeability_QuantityInfo_ReturnsQuantityInfoDescribingQ Assert.Equal(PorousMediumPermeability.Zero, quantityInfo.Zero); Assert.Equal("PorousMediumPermeability", quantityInfo.Name); - Assert.Equal(QuantityType.PorousMediumPermeability, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PorousMediumPermeabilityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -367,7 +355,7 @@ public void ToUnit(PorousMediumPermeabilityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -384,12 +372,8 @@ public void ToUnit_WithSameUnits_AreEqual(PorousMediumPermeabilityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PorousMediumPermeabilityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = PorousMediumPermeability.Units.FirstOrDefault(u => u != PorousMediumPermeability.BaseUnit && u != PorousMediumPermeabilityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PorousMediumPermeabilityUnit.Undefined) - fromUnit = PorousMediumPermeability.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = PorousMediumPermeability.Units.Where(u => u != PorousMediumPermeability.BaseUnit).DefaultIfEmpty(PorousMediumPermeability.BaseUnit).FirstOrDefault(); var quantity = PorousMediumPermeability.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -469,49 +453,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => squaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = PorousMediumPermeability.FromSquareMeters(1); - var b = PorousMediumPermeability.FromSquareMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = PorousMediumPermeability.FromSquareMeters(1); - var b = PorousMediumPermeability.FromSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = PorousMediumPermeability.FromSquareMeters(1); - object b = PorousMediumPermeability.FromSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -541,21 +482,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(squaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PorousMediumPermeabilityUnit.Undefined, PorousMediumPermeability.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PorousMediumPermeabilityUnit)).Cast(); foreach(var unit in units) { - if (unit == PorousMediumPermeabilityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -569,8 +501,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 D", new PorousMediumPermeability(1, PorousMediumPermeabilityUnit.Darcy).ToString()); Assert.Equal("1 µD", new PorousMediumPermeability(1, PorousMediumPermeabilityUnit.Microdarcy).ToString()); @@ -580,7 +512,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -600,10 +532,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m²", new PorousMediumPermeability(0.123456, PorousMediumPermeabilityUnit.SquareMeter).ToString("s1")); Assert.Equal("0.12 m²", new PorousMediumPermeability(0.123456, PorousMediumPermeabilityUnit.SquareMeter).ToString("s2")); Assert.Equal("0.123 m²", new PorousMediumPermeability(0.123456, PorousMediumPermeabilityUnit.SquareMeter).ToString("s3")); @@ -611,7 +543,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -625,29 +557,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m²", new PorousMediumPermeability(0.123456, PorousMediumPermeabilityUnit.SquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -767,13 +698,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PorousMediumPermeabilityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(QuantityType.PorousMediumPermeability, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs index a1414206aa..f34c888d5a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs @@ -230,12 +230,6 @@ public abstract partial class PowerDensityTestsBase : QuantityTestsBase new object[] { PowerDensityUnit.WattPerLiter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new PowerDensity((double)0.0, PowerDensityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -244,7 +238,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PowerDensityUnit.WattPerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -288,14 +281,9 @@ public void PowerDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(PowerDensity.Zero, quantityInfo.Zero); Assert.Equal("PowerDensity", quantityInfo.Name); - Assert.Equal(QuantityType.PowerDensity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PowerDensityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1605,7 +1593,7 @@ public void ToUnit(PowerDensityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1622,12 +1610,8 @@ public void ToUnit_WithSameUnits_AreEqual(PowerDensityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerDensityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = PowerDensity.Units.FirstOrDefault(u => u != PowerDensity.BaseUnit && u != PowerDensityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PowerDensityUnit.Undefined) - fromUnit = PowerDensity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = PowerDensity.Units.Where(u => u != PowerDensity.BaseUnit).DefaultIfEmpty(PowerDensity.BaseUnit).FirstOrDefault(); var quantity = PowerDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1746,49 +1730,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => wattpercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = PowerDensity.FromWattsPerCubicMeter(1); - var b = PowerDensity.FromWattsPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = PowerDensity.FromWattsPerCubicMeter(1); - var b = PowerDensity.FromWattsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = PowerDensity.FromWattsPerCubicMeter(1); - object b = PowerDensity.FromWattsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1818,21 +1759,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PowerDensityUnit.Undefined, PowerDensity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PowerDensityUnit)).Cast(); foreach(var unit in units) { - if (unit == PowerDensityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1846,8 +1778,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 daW/ft³", new PowerDensity(1, PowerDensityUnit.DecawattPerCubicFoot).ToString()); Assert.Equal("1 daW/in³", new PowerDensity(1, PowerDensityUnit.DecawattPerCubicInch).ToString()); @@ -1896,7 +1828,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1955,10 +1887,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W/m³", new PowerDensity(0.123456, PowerDensityUnit.WattPerCubicMeter).ToString("s1")); Assert.Equal("0.12 W/m³", new PowerDensity(0.123456, PowerDensityUnit.WattPerCubicMeter).ToString("s2")); Assert.Equal("0.123 W/m³", new PowerDensity(0.123456, PowerDensityUnit.WattPerCubicMeter).ToString("s3")); @@ -1966,7 +1898,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1980,29 +1912,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W/m³", new PowerDensity(0.123456, PowerDensityUnit.WattPerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2122,13 +2053,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PowerDensityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(QuantityType.PowerDensity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs index 4a6a55f63b..1c09d0842c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs @@ -62,12 +62,6 @@ public abstract partial class PowerRatioTestsBase : QuantityTestsBase new object[] { PowerRatioUnit.DecibelWatt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new PowerRatio((double)0.0, PowerRatioUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -76,7 +70,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PowerRatioUnit.DecibelWatt, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -120,14 +113,9 @@ public void PowerRatio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(PowerRatio.Zero, quantityInfo.Zero); Assert.Equal("PowerRatio", quantityInfo.Name); - Assert.Equal(QuantityType.PowerRatio, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PowerRatioUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -289,7 +277,7 @@ public void ToUnit(PowerRatioUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -306,12 +294,8 @@ public void ToUnit_WithSameUnits_AreEqual(PowerRatioUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerRatioUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = PowerRatio.Units.FirstOrDefault(u => u != PowerRatio.BaseUnit && u != PowerRatioUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PowerRatioUnit.Undefined) - fromUnit = PowerRatio.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = PowerRatio.Units.Where(u => u != PowerRatio.BaseUnit).DefaultIfEmpty(PowerRatio.BaseUnit).FirstOrDefault(); var quantity = PowerRatio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -392,49 +376,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decibelwatt.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = PowerRatio.FromDecibelWatts(1); - var b = PowerRatio.FromDecibelWatts(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = PowerRatio.FromDecibelWatts(1); - var b = PowerRatio.FromDecibelWatts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = PowerRatio.FromDecibelWatts(1); - object b = PowerRatio.FromDecibelWatts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -464,21 +405,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decibelwatt.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PowerRatioUnit.Undefined, PowerRatio.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PowerRatioUnit)).Cast(); foreach(var unit in units) { - if (unit == PowerRatioUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -492,15 +424,15 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 dBmW", new PowerRatio(1, PowerRatioUnit.DecibelMilliwatt).ToString()); Assert.Equal("1 dBW", new PowerRatio(1, PowerRatioUnit.DecibelWatt).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -517,10 +449,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 dBW", new PowerRatio(0.123456, PowerRatioUnit.DecibelWatt).ToString("s1")); Assert.Equal("0.12 dBW", new PowerRatio(0.123456, PowerRatioUnit.DecibelWatt).ToString("s2")); Assert.Equal("0.123 dBW", new PowerRatio(0.123456, PowerRatioUnit.DecibelWatt).ToString("s3")); @@ -528,7 +460,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -542,29 +474,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 dBW", new PowerRatio(0.123456, PowerRatioUnit.DecibelWatt).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -684,13 +615,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PowerRatioUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(QuantityType.PowerRatio, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs index 9c269a8bf1..9fc8623021 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs @@ -38,63 +38,63 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class PowerTestsBase : QuantityTestsBase { - protected abstract double BoilerHorsepowerInOneWatt { get; } - protected abstract double BritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double DecawattsInOneWatt { get; } - protected abstract double DeciwattsInOneWatt { get; } - protected abstract double ElectricalHorsepowerInOneWatt { get; } - protected abstract double FemtowattsInOneWatt { get; } - protected abstract double GigajoulesPerHourInOneWatt { get; } - protected abstract double GigawattsInOneWatt { get; } - protected abstract double HydraulicHorsepowerInOneWatt { get; } - protected abstract double JoulesPerHourInOneWatt { get; } - protected abstract double KilobritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double KilojoulesPerHourInOneWatt { get; } - protected abstract double KilowattsInOneWatt { get; } - protected abstract double MechanicalHorsepowerInOneWatt { get; } - protected abstract double MegabritishThermalUnitsPerHourInOneWatt { get; } - protected abstract double MegajoulesPerHourInOneWatt { get; } - protected abstract double MegawattsInOneWatt { get; } - protected abstract double MetricHorsepowerInOneWatt { get; } - protected abstract double MicrowattsInOneWatt { get; } - protected abstract double MillijoulesPerHourInOneWatt { get; } - protected abstract double MilliwattsInOneWatt { get; } - protected abstract double NanowattsInOneWatt { get; } - protected abstract double PetawattsInOneWatt { get; } - protected abstract double PicowattsInOneWatt { get; } - protected abstract double TerawattsInOneWatt { get; } - protected abstract double WattsInOneWatt { get; } + protected abstract decimal BoilerHorsepowerInOneWatt { get; } + protected abstract decimal BritishThermalUnitsPerHourInOneWatt { get; } + protected abstract decimal DecawattsInOneWatt { get; } + protected abstract decimal DeciwattsInOneWatt { get; } + protected abstract decimal ElectricalHorsepowerInOneWatt { get; } + protected abstract decimal FemtowattsInOneWatt { get; } + protected abstract decimal GigajoulesPerHourInOneWatt { get; } + protected abstract decimal GigawattsInOneWatt { get; } + protected abstract decimal HydraulicHorsepowerInOneWatt { get; } + protected abstract decimal JoulesPerHourInOneWatt { get; } + protected abstract decimal KilobritishThermalUnitsPerHourInOneWatt { get; } + protected abstract decimal KilojoulesPerHourInOneWatt { get; } + protected abstract decimal KilowattsInOneWatt { get; } + protected abstract decimal MechanicalHorsepowerInOneWatt { get; } + protected abstract decimal MegabritishThermalUnitsPerHourInOneWatt { get; } + protected abstract decimal MegajoulesPerHourInOneWatt { get; } + protected abstract decimal MegawattsInOneWatt { get; } + protected abstract decimal MetricHorsepowerInOneWatt { get; } + protected abstract decimal MicrowattsInOneWatt { get; } + protected abstract decimal MillijoulesPerHourInOneWatt { get; } + protected abstract decimal MilliwattsInOneWatt { get; } + protected abstract decimal NanowattsInOneWatt { get; } + protected abstract decimal PetawattsInOneWatt { get; } + protected abstract decimal PicowattsInOneWatt { get; } + protected abstract decimal TerawattsInOneWatt { get; } + protected abstract decimal WattsInOneWatt { get; } // ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double BoilerHorsepowerTolerance { get { return 1e-5; } } - protected virtual double BritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double DecawattsTolerance { get { return 1e-5; } } - protected virtual double DeciwattsTolerance { get { return 1e-5; } } - protected virtual double ElectricalHorsepowerTolerance { get { return 1e-5; } } - protected virtual double FemtowattsTolerance { get { return 1e-5; } } - protected virtual double GigajoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double GigawattsTolerance { get { return 1e-5; } } - protected virtual double HydraulicHorsepowerTolerance { get { return 1e-5; } } - protected virtual double JoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double KilobritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double KilojoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double KilowattsTolerance { get { return 1e-5; } } - protected virtual double MechanicalHorsepowerTolerance { get { return 1e-5; } } - protected virtual double MegabritishThermalUnitsPerHourTolerance { get { return 1e-5; } } - protected virtual double MegajoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double MegawattsTolerance { get { return 1e-5; } } - protected virtual double MetricHorsepowerTolerance { get { return 1e-5; } } - protected virtual double MicrowattsTolerance { get { return 1e-5; } } - protected virtual double MillijoulesPerHourTolerance { get { return 1e-5; } } - protected virtual double MilliwattsTolerance { get { return 1e-5; } } - protected virtual double NanowattsTolerance { get { return 1e-5; } } - protected virtual double PetawattsTolerance { get { return 1e-5; } } - protected virtual double PicowattsTolerance { get { return 1e-5; } } - protected virtual double TerawattsTolerance { get { return 1e-5; } } - protected virtual double WattsTolerance { get { return 1e-5; } } + protected virtual decimal BoilerHorsepowerTolerance { get { return 1e-9m; } } + protected virtual decimal BritishThermalUnitsPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal DecawattsTolerance { get { return 1e-9m; } } + protected virtual decimal DeciwattsTolerance { get { return 1e-9m; } } + protected virtual decimal ElectricalHorsepowerTolerance { get { return 1e-9m; } } + protected virtual decimal FemtowattsTolerance { get { return 1e-9m; } } + protected virtual decimal GigajoulesPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal GigawattsTolerance { get { return 1e-9m; } } + protected virtual decimal HydraulicHorsepowerTolerance { get { return 1e-9m; } } + protected virtual decimal JoulesPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal KilobritishThermalUnitsPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal KilojoulesPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal KilowattsTolerance { get { return 1e-9m; } } + protected virtual decimal MechanicalHorsepowerTolerance { get { return 1e-9m; } } + protected virtual decimal MegabritishThermalUnitsPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal MegajoulesPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal MegawattsTolerance { get { return 1e-9m; } } + protected virtual decimal MetricHorsepowerTolerance { get { return 1e-9m; } } + protected virtual decimal MicrowattsTolerance { get { return 1e-9m; } } + protected virtual decimal MillijoulesPerHourTolerance { get { return 1e-9m; } } + protected virtual decimal MilliwattsTolerance { get { return 1e-9m; } } + protected virtual decimal NanowattsTolerance { get { return 1e-9m; } } + protected virtual decimal PetawattsTolerance { get { return 1e-9m; } } + protected virtual decimal PicowattsTolerance { get { return 1e-9m; } } + protected virtual decimal TerawattsTolerance { get { return 1e-9m; } } + protected virtual decimal WattsTolerance { get { return 1e-9m; } } // ReSharper restore VirtualMemberNeverOverriden.Global - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerUnit unit) + protected (decimal UnitsInBaseUnit, decimal Tolerence) GetConversionFactor(PowerUnit unit) { return unit switch { @@ -158,12 +158,6 @@ public abstract partial class PowerTestsBase : QuantityTestsBase new object[] { PowerUnit.Watt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Power((decimal)0.0, PowerUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -173,7 +167,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PowerUnit.Watt, quantity.Unit); } - [Fact] public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException() { @@ -204,14 +197,9 @@ public void Power_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Power.Zero, quantityInfo.Zero); Assert.Equal("Power", quantityInfo.Name); - Assert.Equal(QuantityType.Power, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PowerUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1062,7 +1050,7 @@ public void ToUnit(PowerUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1079,12 +1067,8 @@ public void ToUnit_WithSameUnits_AreEqual(PowerUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Power.Units.FirstOrDefault(u => u != Power.BaseUnit && u != PowerUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PowerUnit.Undefined) - fromUnit = Power.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Power.Units.Where(u => u != Power.BaseUnit).DefaultIfEmpty(Power.BaseUnit).FirstOrDefault(); var quantity = Power.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1185,49 +1169,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => watt.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Power.FromWatts(1); - var b = Power.FromWatts(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Power.FromWatts(1); - var b = Power.FromWatts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Power.FromWatts(1); - object b = Power.FromWatts(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1257,21 +1198,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(watt.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PowerUnit.Undefined, Power.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PowerUnit)).Cast(); foreach(var unit in units) { - if (unit == PowerUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1285,8 +1217,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 hp(S)", new Power(1, PowerUnit.BoilerHorsepower).ToString()); Assert.Equal("1 Btu/h", new Power(1, PowerUnit.BritishThermalUnitPerHour).ToString()); @@ -1317,7 +1249,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1358,10 +1290,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W", new Power(0.123456m, PowerUnit.Watt).ToString("s1")); Assert.Equal("0.12 W", new Power(0.123456m, PowerUnit.Watt).ToString("s2")); Assert.Equal("0.123 W", new Power(0.123456m, PowerUnit.Watt).ToString("s3")); @@ -1369,7 +1301,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1383,29 +1315,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W", new Power(0.123456m, PowerUnit.Watt).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Power.FromWatts(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Power.FromWatts(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Power.FromWatts(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1525,13 +1456,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PowerUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(QuantityType.Power, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs index a60d00414f..3adc2b3fd7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs @@ -110,12 +110,6 @@ public abstract partial class PressureChangeRateTestsBase : QuantityTestsBase new object[] { PressureChangeRateUnit.PoundForcePerSquareInchPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new PressureChangeRate((double)0.0, PressureChangeRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -124,7 +118,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PressureChangeRateUnit.PascalPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -168,14 +161,9 @@ public void PressureChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(PressureChangeRate.Zero, quantityInfo.Zero); Assert.Equal("PressureChangeRate", quantityInfo.Name); - Assert.Equal(QuantityType.PressureChangeRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PressureChangeRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1297,7 +1285,7 @@ public void ToUnit(PressureChangeRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1314,12 +1302,8 @@ public void ToUnit_WithSameUnits_AreEqual(PressureChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureChangeRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = PressureChangeRate.Units.FirstOrDefault(u => u != PressureChangeRate.BaseUnit && u != PressureChangeRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PressureChangeRateUnit.Undefined) - fromUnit = PressureChangeRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = PressureChangeRate.Units.Where(u => u != PressureChangeRate.BaseUnit).DefaultIfEmpty(PressureChangeRate.BaseUnit).FirstOrDefault(); var quantity = PressureChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1408,49 +1392,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => pascalpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = PressureChangeRate.FromPascalsPerSecond(1); - var b = PressureChangeRate.FromPascalsPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = PressureChangeRate.FromPascalsPerSecond(1); - var b = PressureChangeRate.FromPascalsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = PressureChangeRate.FromPascalsPerSecond(1); - object b = PressureChangeRate.FromPascalsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1480,21 +1421,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(pascalpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PressureChangeRateUnit.Undefined, PressureChangeRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast(); foreach(var unit in units) { - if (unit == PressureChangeRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1508,8 +1440,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 atm/s", new PressureChangeRate(1, PressureChangeRateUnit.AtmospherePerSecond).ToString()); Assert.Equal("1 kPa/min", new PressureChangeRate(1, PressureChangeRateUnit.KilopascalPerMinute).ToString()); @@ -1528,7 +1460,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1557,10 +1489,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Pa/s", new PressureChangeRate(0.123456, PressureChangeRateUnit.PascalPerSecond).ToString("s1")); Assert.Equal("0.12 Pa/s", new PressureChangeRate(0.123456, PressureChangeRateUnit.PascalPerSecond).ToString("s2")); Assert.Equal("0.123 Pa/s", new PressureChangeRate(0.123456, PressureChangeRateUnit.PascalPerSecond).ToString("s3")); @@ -1568,7 +1500,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1582,29 +1514,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Pa/s", new PressureChangeRate(0.123456, PressureChangeRateUnit.PascalPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1724,13 +1655,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PressureChangeRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(QuantityType.PressureChangeRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs index 74f2542ae4..ede372b06b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs @@ -242,12 +242,6 @@ public abstract partial class PressureTestsBase : QuantityTestsBase new object[] { PressureUnit.Torr }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Pressure((double)0.0, PressureUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -256,7 +250,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(PressureUnit.Pascal, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -300,14 +293,9 @@ public void Pressure_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Pressure.Zero, quantityInfo.Zero); Assert.Equal("Pressure", quantityInfo.Name); - Assert.Equal(QuantityType.Pressure, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {PressureUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2645,7 +2633,7 @@ public void ToUnit(PressureUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2662,12 +2650,8 @@ public void ToUnit_WithSameUnits_AreEqual(PressureUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Pressure.Units.FirstOrDefault(u => u != Pressure.BaseUnit && u != PressureUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == PressureUnit.Undefined) - fromUnit = Pressure.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Pressure.Units.Where(u => u != Pressure.BaseUnit).DefaultIfEmpty(Pressure.BaseUnit).FirstOrDefault(); var quantity = Pressure.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2789,49 +2773,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => pascal.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Pressure.FromPascals(1); - var b = Pressure.FromPascals(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Pressure.FromPascals(1); - var b = Pressure.FromPascals(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Pressure.FromPascals(1); - object b = Pressure.FromPascals(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2861,21 +2802,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(pascal.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(PressureUnit.Undefined, Pressure.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(PressureUnit)).Cast(); foreach(var unit in units) { - if (unit == PressureUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2889,8 +2821,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 atm", new Pressure(1, PressureUnit.Atmosphere).ToString()); Assert.Equal("1 bar", new Pressure(1, PressureUnit.Bar).ToString()); @@ -2942,7 +2874,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -3004,10 +2936,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Pa", new Pressure(0.123456, PressureUnit.Pascal).ToString("s1")); Assert.Equal("0.12 Pa", new Pressure(0.123456, PressureUnit.Pascal).ToString("s2")); Assert.Equal("0.123 Pa", new Pressure(0.123456, PressureUnit.Pascal).ToString("s3")); @@ -3015,7 +2947,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -3029,29 +2961,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Pa", new Pressure(0.123456, PressureUnit.Pascal).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Pressure.FromPascals(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Pressure.FromPascals(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -3171,13 +3102,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PressureUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(QuantityType.Pressure, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs index 2b305541a4..c50d42c965 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs @@ -62,12 +62,6 @@ public abstract partial class RatioChangeRateTestsBase : QuantityTestsBase new object[] { RatioChangeRateUnit.PercentPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new RatioChangeRate((double)0.0, RatioChangeRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -76,7 +70,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RatioChangeRateUnit.DecimalFractionPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -120,14 +113,9 @@ public void RatioChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(RatioChangeRate.Zero, quantityInfo.Zero); Assert.Equal("RatioChangeRate", quantityInfo.Name); - Assert.Equal(QuantityType.RatioChangeRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RatioChangeRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -265,7 +253,7 @@ public void ToUnit(RatioChangeRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -282,12 +270,8 @@ public void ToUnit_WithSameUnits_AreEqual(RatioChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioChangeRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = RatioChangeRate.Units.FirstOrDefault(u => u != RatioChangeRate.BaseUnit && u != RatioChangeRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RatioChangeRateUnit.Undefined) - fromUnit = RatioChangeRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = RatioChangeRate.Units.Where(u => u != RatioChangeRate.BaseUnit).DefaultIfEmpty(RatioChangeRate.BaseUnit).FirstOrDefault(); var quantity = RatioChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -364,49 +348,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decimalfractionpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = RatioChangeRate.FromDecimalFractionsPerSecond(1); - var b = RatioChangeRate.FromDecimalFractionsPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = RatioChangeRate.FromDecimalFractionsPerSecond(1); - var b = RatioChangeRate.FromDecimalFractionsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = RatioChangeRate.FromDecimalFractionsPerSecond(1); - object b = RatioChangeRate.FromDecimalFractionsPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -436,21 +377,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decimalfractionpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RatioChangeRateUnit.Undefined, RatioChangeRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RatioChangeRateUnit)).Cast(); foreach(var unit in units) { - if (unit == RatioChangeRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -464,15 +396,15 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 /s", new RatioChangeRate(1, RatioChangeRateUnit.DecimalFractionPerSecond).ToString()); Assert.Equal("1 %/s", new RatioChangeRate(1, RatioChangeRateUnit.PercentPerSecond).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -489,10 +421,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 /s", new RatioChangeRate(0.123456, RatioChangeRateUnit.DecimalFractionPerSecond).ToString("s1")); Assert.Equal("0.12 /s", new RatioChangeRate(0.123456, RatioChangeRateUnit.DecimalFractionPerSecond).ToString("s2")); Assert.Equal("0.123 /s", new RatioChangeRate(0.123456, RatioChangeRateUnit.DecimalFractionPerSecond).ToString("s3")); @@ -500,7 +432,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -514,29 +446,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 /s", new RatioChangeRate(0.123456, RatioChangeRateUnit.DecimalFractionPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -656,13 +587,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RatioChangeRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(QuantityType.RatioChangeRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs index 2f4b8b53ea..9b814437f8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class RatioTestsBase : QuantityTestsBase new object[] { RatioUnit.Percent }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Ratio((double)0.0, RatioUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RatioUnit.DecimalFraction, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void Ratio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Ratio.Zero, quantityInfo.Zero); Assert.Equal("Ratio", quantityInfo.Name); - Assert.Equal(QuantityType.Ratio, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RatioUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -401,7 +389,7 @@ public void ToUnit(RatioUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -418,12 +406,8 @@ public void ToUnit_WithSameUnits_AreEqual(RatioUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Ratio.Units.FirstOrDefault(u => u != Ratio.BaseUnit && u != RatioUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RatioUnit.Undefined) - fromUnit = Ratio.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Ratio.Units.Where(u => u != Ratio.BaseUnit).DefaultIfEmpty(Ratio.BaseUnit).FirstOrDefault(); var quantity = Ratio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -504,49 +488,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decimalfraction.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Ratio.FromDecimalFractions(1); - var b = Ratio.FromDecimalFractions(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Ratio.FromDecimalFractions(1); - var b = Ratio.FromDecimalFractions(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Ratio.FromDecimalFractions(1); - object b = Ratio.FromDecimalFractions(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -576,21 +517,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decimalfraction.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RatioUnit.Undefined, Ratio.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RatioUnit)).Cast(); foreach(var unit in units) { - if (unit == RatioUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -604,8 +536,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1", new Ratio(1, RatioUnit.DecimalFraction).ToString()); Assert.Equal("1 ppb", new Ratio(1, RatioUnit.PartPerBillion).ToString()); @@ -616,7 +548,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -637,10 +569,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1", new Ratio(0.123456, RatioUnit.DecimalFraction).ToString("s1")); Assert.Equal("0.12", new Ratio(0.123456, RatioUnit.DecimalFraction).ToString("s2")); Assert.Equal("0.123", new Ratio(0.123456, RatioUnit.DecimalFraction).ToString("s3")); @@ -648,7 +580,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -662,29 +594,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235", new Ratio(0.123456, RatioUnit.DecimalFraction).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -804,13 +735,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RatioUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(QuantityType.Ratio, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs index e4f4ba5404..1a9eadb03f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactiveEnergyTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class ReactiveEnergyTestsBase : QuantityTestsBase new object[] { ReactiveEnergyUnit.VoltampereReactiveHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ReactiveEnergy((double)0.0, ReactiveEnergyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ReactiveEnergyUnit.VoltampereReactiveHour, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void ReactiveEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ReactiveEnergy.Zero, quantityInfo.Zero); Assert.Equal("ReactiveEnergy", quantityInfo.Name); - Assert.Equal(QuantityType.ReactiveEnergy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ReactiveEnergyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(ReactiveEnergyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReactiveEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReactiveEnergyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ReactiveEnergy.Units.FirstOrDefault(u => u != ReactiveEnergy.BaseUnit && u != ReactiveEnergyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ReactiveEnergyUnit.Undefined) - fromUnit = ReactiveEnergy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ReactiveEnergy.Units.Where(u => u != ReactiveEnergy.BaseUnit).DefaultIfEmpty(ReactiveEnergy.BaseUnit).FirstOrDefault(); var quantity = ReactiveEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltamperereactivehour.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ReactiveEnergy.FromVoltampereReactiveHours(1); - var b = ReactiveEnergy.FromVoltampereReactiveHours(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ReactiveEnergy.FromVoltampereReactiveHours(1); - var b = ReactiveEnergy.FromVoltampereReactiveHours(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ReactiveEnergy.FromVoltampereReactiveHours(1); - object b = ReactiveEnergy.FromVoltampereReactiveHours(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltamperereactivehour.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ReactiveEnergyUnit.Undefined, ReactiveEnergy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast(); foreach(var unit in units) { - if (unit == ReactiveEnergyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kvarh", new ReactiveEnergy(1, ReactiveEnergyUnit.KilovoltampereReactiveHour).ToString()); Assert.Equal("1 Mvarh", new ReactiveEnergy(1, ReactiveEnergyUnit.MegavoltampereReactiveHour).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 varh", new ReactiveEnergy(0.123456, ReactiveEnergyUnit.VoltampereReactiveHour).ToString("s1")); Assert.Equal("0.12 varh", new ReactiveEnergy(0.123456, ReactiveEnergyUnit.VoltampereReactiveHour).ToString("s2")); Assert.Equal("0.123 varh", new ReactiveEnergy(0.123456, ReactiveEnergyUnit.VoltampereReactiveHour).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 varh", new ReactiveEnergy(0.123456, ReactiveEnergyUnit.VoltampereReactiveHour).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ReactiveEnergyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(QuantityType.ReactiveEnergy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs index 91574f5ff5..3f5114f1df 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReactivePowerTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class ReactivePowerTestsBase : QuantityTestsBase new object[] { ReactivePowerUnit.VoltampereReactive }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ReactivePower((double)0.0, ReactivePowerUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ReactivePowerUnit.VoltampereReactive, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void ReactivePower_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ReactivePower.Zero, quantityInfo.Zero); Assert.Equal("ReactivePower", quantityInfo.Name); - Assert.Equal(QuantityType.ReactivePower, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ReactivePowerUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(ReactivePowerUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReactivePowerUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReactivePowerUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ReactivePower.Units.FirstOrDefault(u => u != ReactivePower.BaseUnit && u != ReactivePowerUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ReactivePowerUnit.Undefined) - fromUnit = ReactivePower.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ReactivePower.Units.Where(u => u != ReactivePower.BaseUnit).DefaultIfEmpty(ReactivePower.BaseUnit).FirstOrDefault(); var quantity = ReactivePower.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => voltamperereactive.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ReactivePower.FromVoltamperesReactive(1); - var b = ReactivePower.FromVoltamperesReactive(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ReactivePower.FromVoltamperesReactive(1); - var b = ReactivePower.FromVoltamperesReactive(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ReactivePower.FromVoltamperesReactive(1); - object b = ReactivePower.FromVoltamperesReactive(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltamperereactive.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ReactivePowerUnit.Undefined, ReactivePower.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ReactivePowerUnit)).Cast(); foreach(var unit in units) { - if (unit == ReactivePowerUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 Gvar", new ReactivePower(1, ReactivePowerUnit.GigavoltampereReactive).ToString()); Assert.Equal("1 kvar", new ReactivePower(1, ReactivePowerUnit.KilovoltampereReactive).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 var", new ReactivePower(0.123456, ReactivePowerUnit.VoltampereReactive).ToString("s1")); Assert.Equal("0.12 var", new ReactivePower(0.123456, ReactivePowerUnit.VoltampereReactive).ToString("s2")); Assert.Equal("0.123 var", new ReactivePower(0.123456, ReactivePowerUnit.VoltampereReactive).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 var", new ReactivePower(0.123456, ReactivePowerUnit.VoltampereReactive).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ReactivePowerUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(QuantityType.ReactivePower, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs index e92f1db53c..b2a9d5995a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs @@ -98,12 +98,6 @@ public abstract partial class ReciprocalAreaTestsBase : QuantityTestsBase new object[] { ReciprocalAreaUnit.InverseUsSurveySquareFoot }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ReciprocalArea((double)0.0, ReciprocalAreaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -112,7 +106,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ReciprocalAreaUnit.InverseSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -156,14 +149,9 @@ public void ReciprocalArea_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(ReciprocalArea.Zero, quantityInfo.Zero); Assert.Equal("ReciprocalArea", quantityInfo.Name); - Assert.Equal(QuantityType.ReciprocalArea, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ReciprocalAreaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -571,7 +559,7 @@ public void ToUnit(ReciprocalAreaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -588,12 +576,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReciprocalAreaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalAreaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ReciprocalArea.Units.FirstOrDefault(u => u != ReciprocalArea.BaseUnit && u != ReciprocalAreaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ReciprocalAreaUnit.Undefined) - fromUnit = ReciprocalArea.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ReciprocalArea.Units.Where(u => u != ReciprocalArea.BaseUnit).DefaultIfEmpty(ReciprocalArea.BaseUnit).FirstOrDefault(); var quantity = ReciprocalArea.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -679,49 +663,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => inversesquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ReciprocalArea.FromInverseSquareMeters(1); - var b = ReciprocalArea.FromInverseSquareMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ReciprocalArea.FromInverseSquareMeters(1); - var b = ReciprocalArea.FromInverseSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ReciprocalArea.FromInverseSquareMeters(1); - object b = ReciprocalArea.FromInverseSquareMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -751,21 +692,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(inversesquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ReciprocalAreaUnit.Undefined, ReciprocalArea.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ReciprocalAreaUnit)).Cast(); foreach(var unit in units) { - if (unit == ReciprocalAreaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -779,8 +711,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm⁻²", new ReciprocalArea(1, ReciprocalAreaUnit.InverseSquareCentimeter).ToString()); Assert.Equal("1 dm⁻²", new ReciprocalArea(1, ReciprocalAreaUnit.InverseSquareDecimeter).ToString()); @@ -796,7 +728,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -822,10 +754,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m⁻²", new ReciprocalArea(0.123456, ReciprocalAreaUnit.InverseSquareMeter).ToString("s1")); Assert.Equal("0.12 m⁻²", new ReciprocalArea(0.123456, ReciprocalAreaUnit.InverseSquareMeter).ToString("s2")); Assert.Equal("0.123 m⁻²", new ReciprocalArea(0.123456, ReciprocalAreaUnit.InverseSquareMeter).ToString("s3")); @@ -833,7 +765,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -847,29 +779,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m⁻²", new ReciprocalArea(0.123456, ReciprocalAreaUnit.InverseSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -989,13 +920,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ReciprocalAreaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(QuantityType.ReciprocalArea, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs index 23d69f71cb..b1bb4ae5d0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs @@ -94,12 +94,6 @@ public abstract partial class ReciprocalLengthTestsBase : QuantityTestsBase new object[] { ReciprocalLengthUnit.InverseYard }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ReciprocalLength((double)0.0, ReciprocalLengthUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -108,7 +102,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ReciprocalLengthUnit.InverseMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -152,14 +145,9 @@ public void ReciprocalLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(ReciprocalLength.Zero, quantityInfo.Zero); Assert.Equal("ReciprocalLength", quantityInfo.Name); - Assert.Equal(QuantityType.ReciprocalLength, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ReciprocalLengthUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -777,7 +765,7 @@ public void ToUnit(ReciprocalLengthUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -794,12 +782,8 @@ public void ToUnit_WithSameUnits_AreEqual(ReciprocalLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalLengthUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ReciprocalLength.Units.FirstOrDefault(u => u != ReciprocalLength.BaseUnit && u != ReciprocalLengthUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ReciprocalLengthUnit.Undefined) - fromUnit = ReciprocalLength.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ReciprocalLength.Units.Where(u => u != ReciprocalLength.BaseUnit).DefaultIfEmpty(ReciprocalLength.BaseUnit).FirstOrDefault(); var quantity = ReciprocalLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -884,49 +868,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => inversemeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ReciprocalLength.FromInverseMeters(1); - var b = ReciprocalLength.FromInverseMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ReciprocalLength.FromInverseMeters(1); - var b = ReciprocalLength.FromInverseMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ReciprocalLength.FromInverseMeters(1); - object b = ReciprocalLength.FromInverseMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -956,21 +897,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(inversemeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ReciprocalLengthUnit.Undefined, ReciprocalLength.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ReciprocalLengthUnit)).Cast(); foreach(var unit in units) { - if (unit == ReciprocalLengthUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -984,8 +916,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm⁻¹", new ReciprocalLength(1, ReciprocalLengthUnit.InverseCentimeter).ToString()); Assert.Equal("1 ft⁻¹", new ReciprocalLength(1, ReciprocalLengthUnit.InverseFoot).ToString()); @@ -1000,7 +932,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1025,10 +957,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m⁻¹", new ReciprocalLength(0.123456, ReciprocalLengthUnit.InverseMeter).ToString("s1")); Assert.Equal("0.12 m⁻¹", new ReciprocalLength(0.123456, ReciprocalLengthUnit.InverseMeter).ToString("s2")); Assert.Equal("0.123 m⁻¹", new ReciprocalLength(0.123456, ReciprocalLengthUnit.InverseMeter).ToString("s3")); @@ -1036,7 +968,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1050,29 +982,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m⁻¹", new ReciprocalLength(0.123456, ReciprocalLengthUnit.InverseMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1192,13 +1123,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ReciprocalLengthUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(QuantityType.ReciprocalLength, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs index 5506c7fde1..9db7d30654 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class RelativeHumidityTestsBase : QuantityTestsBase new object[] { RelativeHumidityUnit.Percent }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new RelativeHumidity((double)0.0, RelativeHumidityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RelativeHumidityUnit.Percent, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void RelativeHumidity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(RelativeHumidity.Zero, quantityInfo.Zero); Assert.Equal("RelativeHumidity", quantityInfo.Name); - Assert.Equal(QuantityType.RelativeHumidity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RelativeHumidityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(RelativeHumidityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(RelativeHumidityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RelativeHumidityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = RelativeHumidity.Units.FirstOrDefault(u => u != RelativeHumidity.BaseUnit && u != RelativeHumidityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RelativeHumidityUnit.Undefined) - fromUnit = RelativeHumidity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = RelativeHumidity.Units.Where(u => u != RelativeHumidity.BaseUnit).DefaultIfEmpty(RelativeHumidity.BaseUnit).FirstOrDefault(); var quantity = RelativeHumidity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => percent.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = RelativeHumidity.FromPercent(1); - var b = RelativeHumidity.FromPercent(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = RelativeHumidity.FromPercent(1); - var b = RelativeHumidity.FromPercent(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = RelativeHumidity.FromPercent(1); - object b = RelativeHumidity.FromPercent(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(percent.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RelativeHumidityUnit.Undefined, RelativeHumidity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RelativeHumidityUnit)).Cast(); foreach(var unit in units) { - if (unit == RelativeHumidityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 %RH", new RelativeHumidity(1, RelativeHumidityUnit.Percent).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 %RH", new RelativeHumidity(0.123456, RelativeHumidityUnit.Percent).ToString("s1")); Assert.Equal("0.12 %RH", new RelativeHumidity(0.123456, RelativeHumidityUnit.Percent).ToString("s2")); Assert.Equal("0.123 %RH", new RelativeHumidity(0.123456, RelativeHumidityUnit.Percent).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 %RH", new RelativeHumidity(0.123456, RelativeHumidityUnit.Percent).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RelativeHumidityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(QuantityType.RelativeHumidity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs index 4ce7eced49..2017883439 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class RotationalAccelerationTestsBase : QuantityTestsBas new object[] { RotationalAccelerationUnit.RevolutionPerSecondSquared }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new RotationalAcceleration((double)0.0, RotationalAccelerationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RotationalAccelerationUnit.RadianPerSecondSquared, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void RotationalAcceleration_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(RotationalAcceleration.Zero, quantityInfo.Zero); Assert.Equal("RotationalAcceleration", quantityInfo.Name); - Assert.Equal(QuantityType.RotationalAcceleration, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RotationalAccelerationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -357,7 +345,7 @@ public void ToUnit(RotationalAccelerationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -374,12 +362,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalAccelerationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalAccelerationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = RotationalAcceleration.Units.FirstOrDefault(u => u != RotationalAcceleration.BaseUnit && u != RotationalAccelerationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RotationalAccelerationUnit.Undefined) - fromUnit = RotationalAcceleration.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = RotationalAcceleration.Units.Where(u => u != RotationalAcceleration.BaseUnit).DefaultIfEmpty(RotationalAcceleration.BaseUnit).FirstOrDefault(); var quantity = RotationalAcceleration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -458,49 +442,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => radianpersecondsquared.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = RotationalAcceleration.FromRadiansPerSecondSquared(1); - var b = RotationalAcceleration.FromRadiansPerSecondSquared(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = RotationalAcceleration.FromRadiansPerSecondSquared(1); - var b = RotationalAcceleration.FromRadiansPerSecondSquared(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = RotationalAcceleration.FromRadiansPerSecondSquared(1); - object b = RotationalAcceleration.FromRadiansPerSecondSquared(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -530,21 +471,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(radianpersecondsquared.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalAccelerationUnit.Undefined, RotationalAcceleration.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast(); foreach(var unit in units) { - if (unit == RotationalAccelerationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -558,8 +490,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 °/s²", new RotationalAcceleration(1, RotationalAccelerationUnit.DegreePerSecondSquared).ToString()); Assert.Equal("1 rad/s²", new RotationalAcceleration(1, RotationalAccelerationUnit.RadianPerSecondSquared).ToString()); @@ -568,7 +500,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -587,10 +519,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 rad/s²", new RotationalAcceleration(0.123456, RotationalAccelerationUnit.RadianPerSecondSquared).ToString("s1")); Assert.Equal("0.12 rad/s²", new RotationalAcceleration(0.123456, RotationalAccelerationUnit.RadianPerSecondSquared).ToString("s2")); Assert.Equal("0.123 rad/s²", new RotationalAcceleration(0.123456, RotationalAccelerationUnit.RadianPerSecondSquared).ToString("s3")); @@ -598,7 +530,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -612,29 +544,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 rad/s²", new RotationalAcceleration(0.123456, RotationalAccelerationUnit.RadianPerSecondSquared).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -754,13 +685,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalAccelerationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(QuantityType.RotationalAcceleration, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs index 153d97a2d8..7a2a199d65 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs @@ -106,12 +106,6 @@ public abstract partial class RotationalSpeedTestsBase : QuantityTestsBase new object[] { RotationalSpeedUnit.RevolutionPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new RotationalSpeed((double)0.0, RotationalSpeedUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -120,7 +114,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RotationalSpeedUnit.RadianPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -164,14 +157,9 @@ public void RotationalSpeed_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(RotationalSpeed.Zero, quantityInfo.Zero); Assert.Equal("RotationalSpeed", quantityInfo.Name); - Assert.Equal(QuantityType.RotationalSpeed, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RotationalSpeedUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1071,7 +1059,7 @@ public void ToUnit(RotationalSpeedUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1088,12 +1076,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalSpeedUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalSpeedUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = RotationalSpeed.Units.FirstOrDefault(u => u != RotationalSpeed.BaseUnit && u != RotationalSpeedUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RotationalSpeedUnit.Undefined) - fromUnit = RotationalSpeed.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = RotationalSpeed.Units.Where(u => u != RotationalSpeed.BaseUnit).DefaultIfEmpty(RotationalSpeed.BaseUnit).FirstOrDefault(); var quantity = RotationalSpeed.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1181,49 +1165,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => radianpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = RotationalSpeed.FromRadiansPerSecond(1); - var b = RotationalSpeed.FromRadiansPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = RotationalSpeed.FromRadiansPerSecond(1); - var b = RotationalSpeed.FromRadiansPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = RotationalSpeed.FromRadiansPerSecond(1); - object b = RotationalSpeed.FromRadiansPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1253,21 +1194,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(radianpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalSpeedUnit.Undefined, RotationalSpeed.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast(); foreach(var unit in units) { - if (unit == RotationalSpeedUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1281,8 +1213,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 crad/s", new RotationalSpeed(1, RotationalSpeedUnit.CentiradianPerSecond).ToString()); Assert.Equal("1 drad/s", new RotationalSpeed(1, RotationalSpeedUnit.DeciradianPerSecond).ToString()); @@ -1300,7 +1232,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1328,10 +1260,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 rad/s", new RotationalSpeed(0.123456, RotationalSpeedUnit.RadianPerSecond).ToString("s1")); Assert.Equal("0.12 rad/s", new RotationalSpeed(0.123456, RotationalSpeedUnit.RadianPerSecond).ToString("s2")); Assert.Equal("0.123 rad/s", new RotationalSpeed(0.123456, RotationalSpeedUnit.RadianPerSecond).ToString("s3")); @@ -1339,7 +1271,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1353,29 +1285,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 rad/s", new RotationalSpeed(0.123456, RotationalSpeedUnit.RadianPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1495,13 +1426,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalSpeedUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(QuantityType.RotationalSpeed, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs index af56920147..3c240d882b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs @@ -74,12 +74,6 @@ public abstract partial class RotationalStiffnessPerLengthTestsBase : QuantityTe new object[] { RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new RotationalStiffnessPerLength((double)0.0, RotationalStiffnessPerLengthUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -88,7 +82,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -132,14 +125,9 @@ public void RotationalStiffnessPerLength_QuantityInfo_ReturnsQuantityInfoDescrib Assert.Equal(RotationalStiffnessPerLength.Zero, quantityInfo.Zero); Assert.Equal("RotationalStiffnessPerLength", quantityInfo.Name); - Assert.Equal(QuantityType.RotationalStiffnessPerLength, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RotationalStiffnessPerLengthUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -559,7 +547,7 @@ public void ToUnit(RotationalStiffnessPerLengthUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -576,12 +564,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessPerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffnessPerLengthUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = RotationalStiffnessPerLength.Units.FirstOrDefault(u => u != RotationalStiffnessPerLength.BaseUnit && u != RotationalStiffnessPerLengthUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RotationalStiffnessPerLengthUnit.Undefined) - fromUnit = RotationalStiffnessPerLength.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = RotationalStiffnessPerLength.Units.Where(u => u != RotationalStiffnessPerLength.BaseUnit).DefaultIfEmpty(RotationalStiffnessPerLength.BaseUnit).FirstOrDefault(); var quantity = RotationalStiffnessPerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -661,49 +645,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonmeterperradianpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - var b = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - var b = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - object b = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -733,21 +674,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonmeterperradianpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalStiffnessPerLengthUnit.Undefined, RotationalStiffnessPerLength.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast(); foreach(var unit in units) { - if (unit == RotationalStiffnessPerLengthUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -761,8 +693,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kN·m/rad/m", new RotationalStiffnessPerLength(1, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter).ToString()); Assert.Equal("1 kipf·ft/°/ft", new RotationalStiffnessPerLength(1, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot).ToString()); @@ -772,7 +704,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -792,10 +724,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N·m/rad/m", new RotationalStiffnessPerLength(0.123456, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter).ToString("s1")); Assert.Equal("0.12 N·m/rad/m", new RotationalStiffnessPerLength(0.123456, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter).ToString("s2")); Assert.Equal("0.123 N·m/rad/m", new RotationalStiffnessPerLength(0.123456, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter).ToString("s3")); @@ -803,7 +735,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -817,29 +749,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N·m/rad/m", new RotationalStiffnessPerLength(0.123456, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -959,13 +890,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalStiffnessPerLengthUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(QuantityType.RotationalStiffnessPerLength, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs index 14e605179b..b7ef79305b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs @@ -186,12 +186,6 @@ public abstract partial class RotationalStiffnessTestsBase : QuantityTestsBase new object[] { RotationalStiffnessUnit.PoundForceFootPerDegrees }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new RotationalStiffness((double)0.0, RotationalStiffnessUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -200,7 +194,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -244,14 +237,9 @@ public void RotationalStiffness_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(RotationalStiffness.Zero, quantityInfo.Zero); Assert.Equal("RotationalStiffness", quantityInfo.Name); - Assert.Equal(QuantityType.RotationalStiffness, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {RotationalStiffnessUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2803,7 +2791,7 @@ public void ToUnit(RotationalStiffnessUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2820,12 +2808,8 @@ public void ToUnit_WithSameUnits_AreEqual(RotationalStiffnessUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffnessUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = RotationalStiffness.Units.FirstOrDefault(u => u != RotationalStiffness.BaseUnit && u != RotationalStiffnessUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == RotationalStiffnessUnit.Undefined) - fromUnit = RotationalStiffness.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = RotationalStiffness.Units.Where(u => u != RotationalStiffness.BaseUnit).DefaultIfEmpty(RotationalStiffness.BaseUnit).FirstOrDefault(); var quantity = RotationalStiffness.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2933,49 +2917,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonmeterperradian.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = RotationalStiffness.FromNewtonMetersPerRadian(1); - var b = RotationalStiffness.FromNewtonMetersPerRadian(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = RotationalStiffness.FromNewtonMetersPerRadian(1); - var b = RotationalStiffness.FromNewtonMetersPerRadian(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = RotationalStiffness.FromNewtonMetersPerRadian(1); - object b = RotationalStiffness.FromNewtonMetersPerRadian(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -3005,21 +2946,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonmeterperradian.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(RotationalStiffnessUnit.Undefined, RotationalStiffness.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast(); foreach(var unit in units) { - if (unit == RotationalStiffnessUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -3033,8 +2965,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cN·m/deg", new RotationalStiffness(1, RotationalStiffnessUnit.CentinewtonMeterPerDegree).ToString()); Assert.Equal("1 cN·mm/deg", new RotationalStiffness(1, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree).ToString()); @@ -3072,7 +3004,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -3120,10 +3052,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N·m/rad", new RotationalStiffness(0.123456, RotationalStiffnessUnit.NewtonMeterPerRadian).ToString("s1")); Assert.Equal("0.12 N·m/rad", new RotationalStiffness(0.123456, RotationalStiffnessUnit.NewtonMeterPerRadian).ToString("s2")); Assert.Equal("0.123 N·m/rad", new RotationalStiffness(0.123456, RotationalStiffnessUnit.NewtonMeterPerRadian).ToString("s3")); @@ -3131,7 +3063,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -3145,29 +3077,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N·m/rad", new RotationalStiffness(0.123456, RotationalStiffnessUnit.NewtonMeterPerRadian).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -3287,13 +3218,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalStiffnessUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(QuantityType.RotationalStiffness, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs index bf9e59fcde..029b7b9881 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class ScalarTestsBase : QuantityTestsBase new object[] { ScalarUnit.Amount }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Scalar((double)0.0, ScalarUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ScalarUnit.Amount, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void Scalar_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Scalar.Zero, quantityInfo.Zero); Assert.Equal("Scalar", quantityInfo.Name); - Assert.Equal(QuantityType.Scalar, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ScalarUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(ScalarUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(ScalarUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ScalarUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Scalar.Units.FirstOrDefault(u => u != Scalar.BaseUnit && u != ScalarUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ScalarUnit.Undefined) - fromUnit = Scalar.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Scalar.Units.Where(u => u != Scalar.BaseUnit).DefaultIfEmpty(Scalar.BaseUnit).FirstOrDefault(); var quantity = Scalar.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => amount.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Scalar.FromAmount(1); - var b = Scalar.FromAmount(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Scalar.FromAmount(1); - var b = Scalar.FromAmount(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Scalar.FromAmount(1); - object b = Scalar.FromAmount(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(amount.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ScalarUnit.Undefined, Scalar.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ScalarUnit)).Cast(); foreach(var unit in units) { - if (unit == ScalarUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1", new Scalar(1, ScalarUnit.Amount).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1", new Scalar(0.123456, ScalarUnit.Amount).ToString("s1")); Assert.Equal("0.12", new Scalar(0.123456, ScalarUnit.Amount).ToString("s2")); Assert.Equal("0.123", new Scalar(0.123456, ScalarUnit.Amount).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235", new Scalar(0.123456, ScalarUnit.Amount).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Scalar.FromAmount(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Scalar.FromAmount(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ScalarUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(QuantityType.Scalar, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs index 71db457ae6..6e5364347d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class SolidAngleTestsBase : QuantityTestsBase new object[] { SolidAngleUnit.Steradian }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new SolidAngle((double)0.0, SolidAngleUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SolidAngleUnit.Steradian, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void SolidAngle_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(SolidAngle.Zero, quantityInfo.Zero); Assert.Equal("SolidAngle", quantityInfo.Name); - Assert.Equal(QuantityType.SolidAngle, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SolidAngleUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(SolidAngleUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(SolidAngleUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SolidAngleUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = SolidAngle.Units.FirstOrDefault(u => u != SolidAngle.BaseUnit && u != SolidAngleUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SolidAngleUnit.Undefined) - fromUnit = SolidAngle.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = SolidAngle.Units.Where(u => u != SolidAngle.BaseUnit).DefaultIfEmpty(SolidAngle.BaseUnit).FirstOrDefault(); var quantity = SolidAngle.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => steradian.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = SolidAngle.FromSteradians(1); - var b = SolidAngle.FromSteradians(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = SolidAngle.FromSteradians(1); - var b = SolidAngle.FromSteradians(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = SolidAngle.FromSteradians(1); - object b = SolidAngle.FromSteradians(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(steradian.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SolidAngleUnit.Undefined, SolidAngle.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SolidAngleUnit)).Cast(); foreach(var unit in units) { - if (unit == SolidAngleUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 sr", new SolidAngle(1, SolidAngleUnit.Steradian).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 sr", new SolidAngle(0.123456, SolidAngleUnit.Steradian).ToString("s1")); Assert.Equal("0.12 sr", new SolidAngle(0.123456, SolidAngleUnit.Steradian).ToString("s2")); Assert.Equal("0.123 sr", new SolidAngle(0.123456, SolidAngleUnit.Steradian).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 sr", new SolidAngle(0.123456, SolidAngleUnit.Steradian).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = SolidAngle.FromSteradians(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SolidAngleUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(QuantityType.SolidAngle, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs index cf91ab214f..5c87add75e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs @@ -170,12 +170,6 @@ public abstract partial class SpecificEnergyTestsBase : QuantityTestsBase new object[] { SpecificEnergyUnit.WattHourPerPound }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new SpecificEnergy((double)0.0, SpecificEnergyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -184,7 +178,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SpecificEnergyUnit.JoulePerKilogram, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -228,14 +221,9 @@ public void SpecificEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(SpecificEnergy.Zero, quantityInfo.Zero); Assert.Equal("SpecificEnergy", quantityInfo.Name); - Assert.Equal(QuantityType.SpecificEnergy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SpecificEnergyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1183,7 +1171,7 @@ public void ToUnit(SpecificEnergyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1200,12 +1188,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificEnergyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEnergyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = SpecificEnergy.Units.FirstOrDefault(u => u != SpecificEnergy.BaseUnit && u != SpecificEnergyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SpecificEnergyUnit.Undefined) - fromUnit = SpecificEnergy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = SpecificEnergy.Units.Where(u => u != SpecificEnergy.BaseUnit).DefaultIfEmpty(SpecificEnergy.BaseUnit).FirstOrDefault(); var quantity = SpecificEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1309,49 +1293,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => jouleperkilogram.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = SpecificEnergy.FromJoulesPerKilogram(1); - var b = SpecificEnergy.FromJoulesPerKilogram(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = SpecificEnergy.FromJoulesPerKilogram(1); - var b = SpecificEnergy.FromJoulesPerKilogram(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = SpecificEnergy.FromJoulesPerKilogram(1); - object b = SpecificEnergy.FromJoulesPerKilogram(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1381,21 +1322,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(jouleperkilogram.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificEnergyUnit.Undefined, SpecificEnergy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast(); foreach(var unit in units) { - if (unit == SpecificEnergyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1409,8 +1341,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 btu/lb", new SpecificEnergy(1, SpecificEnergyUnit.BtuPerPound).ToString()); Assert.Equal("1 cal/g", new SpecificEnergy(1, SpecificEnergyUnit.CaloriePerGram).ToString()); @@ -1444,7 +1376,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1488,10 +1420,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/kg", new SpecificEnergy(0.123456, SpecificEnergyUnit.JoulePerKilogram).ToString("s1")); Assert.Equal("0.12 J/kg", new SpecificEnergy(0.123456, SpecificEnergyUnit.JoulePerKilogram).ToString("s2")); Assert.Equal("0.123 J/kg", new SpecificEnergy(0.123456, SpecificEnergyUnit.JoulePerKilogram).ToString("s3")); @@ -1499,7 +1431,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1513,29 +1445,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/kg", new SpecificEnergy(0.123456, SpecificEnergyUnit.JoulePerKilogram).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1655,13 +1586,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificEnergyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(QuantityType.SpecificEnergy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs index 086c969278..af43023212 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs @@ -90,12 +90,6 @@ public abstract partial class SpecificEntropyTestsBase : QuantityTestsBase new object[] { SpecificEntropyUnit.MegajoulePerKilogramKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new SpecificEntropy((double)0.0, SpecificEntropyUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -104,7 +98,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SpecificEntropyUnit.JoulePerKilogramKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -148,14 +141,9 @@ public void SpecificEntropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(SpecificEntropy.Zero, quantityInfo.Zero); Assert.Equal("SpecificEntropy", quantityInfo.Name); - Assert.Equal(QuantityType.SpecificEntropy, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SpecificEntropyUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -527,7 +515,7 @@ public void ToUnit(SpecificEntropyUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -544,12 +532,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificEntropyUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEntropyUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = SpecificEntropy.Units.FirstOrDefault(u => u != SpecificEntropy.BaseUnit && u != SpecificEntropyUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SpecificEntropyUnit.Undefined) - fromUnit = SpecificEntropy.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = SpecificEntropy.Units.Where(u => u != SpecificEntropy.BaseUnit).DefaultIfEmpty(SpecificEntropy.BaseUnit).FirstOrDefault(); var quantity = SpecificEntropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -633,49 +617,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => jouleperkilogramkelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - var b = SpecificEntropy.FromJoulesPerKilogramKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - var b = SpecificEntropy.FromJoulesPerKilogramKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - object b = SpecificEntropy.FromJoulesPerKilogramKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -705,21 +646,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(jouleperkilogramkelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificEntropyUnit.Undefined, SpecificEntropy.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast(); foreach(var unit in units) { - if (unit == SpecificEntropyUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -733,8 +665,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 BTU/lb·°F", new SpecificEntropy(1, SpecificEntropyUnit.BtuPerPoundFahrenheit).ToString()); Assert.Equal("1 cal/g.K", new SpecificEntropy(1, SpecificEntropyUnit.CaloriePerGramKelvin).ToString()); @@ -748,7 +680,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -772,10 +704,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/kg.K", new SpecificEntropy(0.123456, SpecificEntropyUnit.JoulePerKilogramKelvin).ToString("s1")); Assert.Equal("0.12 J/kg.K", new SpecificEntropy(0.123456, SpecificEntropyUnit.JoulePerKilogramKelvin).ToString("s2")); Assert.Equal("0.123 J/kg.K", new SpecificEntropy(0.123456, SpecificEntropyUnit.JoulePerKilogramKelvin).ToString("s3")); @@ -783,7 +715,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -797,29 +729,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/kg.K", new SpecificEntropy(0.123456, SpecificEntropyUnit.JoulePerKilogramKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -939,13 +870,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificEntropyUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(QuantityType.SpecificEntropy, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs index d8eb411eb8..746c342333 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class SpecificFuelConsumptionTestsBase : QuantityTestsBa new object[] { SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new SpecificFuelConsumption((double)0.0, SpecificFuelConsumptionUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void SpecificFuelConsumption_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(SpecificFuelConsumption.Zero, quantityInfo.Zero); Assert.Equal("SpecificFuelConsumption", quantityInfo.Name); - Assert.Equal(QuantityType.SpecificFuelConsumption, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SpecificFuelConsumptionUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -214,21 +202,21 @@ public void Parse() { try { - var parsed = SpecificFuelConsumption.Parse("1 g/(kN·s)", CultureInfo.GetCultureInfo("en-US")); + var parsed = SpecificFuelConsumption.Parse("1 g/(kN�s)", CultureInfo.GetCultureInfo("en-US")); AssertEx.EqualTolerance(1, parsed.GramsPerKiloNewtonSecond, GramsPerKiloNewtonSecondTolerance); Assert.Equal(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, parsed.Unit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } try { - var parsed = SpecificFuelConsumption.Parse("1 kg/(kgf·h)", CultureInfo.GetCultureInfo("en-US")); + var parsed = SpecificFuelConsumption.Parse("1 kg/(kgf�h)", CultureInfo.GetCultureInfo("en-US")); AssertEx.EqualTolerance(1, parsed.KilogramsPerKilogramForceHour, KilogramsPerKilogramForceHourTolerance); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, parsed.Unit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } try { - var parsed = SpecificFuelConsumption.Parse("1 kg/(kN·s)", CultureInfo.GetCultureInfo("en-US")); + var parsed = SpecificFuelConsumption.Parse("1 kg/(kN�s)", CultureInfo.GetCultureInfo("en-US")); AssertEx.EqualTolerance(1, parsed.KilogramsPerKiloNewtonSecond, KilogramsPerKiloNewtonSecondTolerance); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, parsed.Unit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } @@ -246,19 +234,19 @@ public void Parse() public void TryParse() { { - Assert.True(SpecificFuelConsumption.TryParse("1 g/(kN·s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); + Assert.True(SpecificFuelConsumption.TryParse("1 g/(kN�s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); AssertEx.EqualTolerance(1, parsed.GramsPerKiloNewtonSecond, GramsPerKiloNewtonSecondTolerance); Assert.Equal(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, parsed.Unit); } { - Assert.True(SpecificFuelConsumption.TryParse("1 kg/(kgf·h)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); + Assert.True(SpecificFuelConsumption.TryParse("1 kg/(kgf�h)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); AssertEx.EqualTolerance(1, parsed.KilogramsPerKilogramForceHour, KilogramsPerKilogramForceHourTolerance); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, parsed.Unit); } { - Assert.True(SpecificFuelConsumption.TryParse("1 kg/(kN·s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); + Assert.True(SpecificFuelConsumption.TryParse("1 kg/(kN�s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); AssertEx.EqualTolerance(1, parsed.KilogramsPerKiloNewtonSecond, KilogramsPerKiloNewtonSecondTolerance); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, parsed.Unit); } @@ -276,19 +264,19 @@ public void ParseUnit() { try { - var parsedUnit = SpecificFuelConsumption.ParseUnit("g/(kN·s)", CultureInfo.GetCultureInfo("en-US")); + var parsedUnit = SpecificFuelConsumption.ParseUnit("g/(kN�s)", CultureInfo.GetCultureInfo("en-US")); Assert.Equal(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, parsedUnit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } try { - var parsedUnit = SpecificFuelConsumption.ParseUnit("kg/(kgf·h)", CultureInfo.GetCultureInfo("en-US")); + var parsedUnit = SpecificFuelConsumption.ParseUnit("kg/(kgf�h)", CultureInfo.GetCultureInfo("en-US")); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, parsedUnit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } try { - var parsedUnit = SpecificFuelConsumption.ParseUnit("kg/(kN·s)", CultureInfo.GetCultureInfo("en-US")); + var parsedUnit = SpecificFuelConsumption.ParseUnit("kg/(kN�s)", CultureInfo.GetCultureInfo("en-US")); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, parsedUnit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } @@ -304,17 +292,17 @@ public void ParseUnit() public void TryParseUnit() { { - Assert.True(SpecificFuelConsumption.TryParseUnit("g/(kN·s)", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); + Assert.True(SpecificFuelConsumption.TryParseUnit("g/(kN�s)", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); Assert.Equal(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, parsedUnit); } { - Assert.True(SpecificFuelConsumption.TryParseUnit("kg/(kgf·h)", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); + Assert.True(SpecificFuelConsumption.TryParseUnit("kg/(kgf�h)", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, parsedUnit); } { - Assert.True(SpecificFuelConsumption.TryParseUnit("kg/(kN·s)", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); + Assert.True(SpecificFuelConsumption.TryParseUnit("kg/(kN�s)", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, parsedUnit); } @@ -333,7 +321,7 @@ public void ToUnit(SpecificFuelConsumptionUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificFuelConsumptionUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificFuelConsumptionUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = SpecificFuelConsumption.Units.FirstOrDefault(u => u != SpecificFuelConsumption.BaseUnit && u != SpecificFuelConsumptionUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SpecificFuelConsumptionUnit.Undefined) - fromUnit = SpecificFuelConsumption.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = SpecificFuelConsumption.Units.Where(u => u != SpecificFuelConsumption.BaseUnit).DefaultIfEmpty(SpecificFuelConsumption.BaseUnit).FirstOrDefault(); var quantity = SpecificFuelConsumption.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => gramperkilonewtonsecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1); - var b = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1); - var b = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1); - object b = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(gramperkilonewtonsecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificFuelConsumptionUnit.Undefined, SpecificFuelConsumption.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SpecificFuelConsumptionUnit)).Cast(); foreach(var unit in units) { - if (unit == SpecificFuelConsumptionUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,17 +466,17 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { - Assert.Equal("1 g/(kN·s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString()); - Assert.Equal("1 kg/(kgf·h)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour).ToString()); - Assert.Equal("1 kg/(kN·s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond).ToString()); + Assert.Equal("1 g/(kN�s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString()); + Assert.Equal("1 kg/(kgf�h)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour).ToString()); + Assert.Equal("1 kg/(kN�s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond).ToString()); Assert.Equal("1 lb/(lbf·h)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -554,27 +486,27 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture // Chose this culture, because we don't currently have any abbreviations mapped for that culture and we expect the en-US to be used as fallback. var swedishCulture = CultureInfo.GetCultureInfo("sv-SE"); - Assert.Equal("1 g/(kN·s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString(swedishCulture)); - Assert.Equal("1 kg/(kgf·h)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour).ToString(swedishCulture)); - Assert.Equal("1 kg/(kN·s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond).ToString(swedishCulture)); + Assert.Equal("1 g/(kN�s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString(swedishCulture)); + Assert.Equal("1 kg/(kgf�h)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour).ToString(swedishCulture)); + Assert.Equal("1 kg/(kN�s)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond).ToString(swedishCulture)); Assert.Equal("1 lb/(lbf·h)", new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour).ToString(swedishCulture)); } [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("0.1 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s1")); - Assert.Equal("0.12 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s2")); - Assert.Equal("0.123 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s3")); - Assert.Equal("0.1235 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s4")); + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + Assert.Equal("0.1 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s1")); + Assert.Equal("0.12 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s2")); + Assert.Equal("0.123 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s3")); + Assert.Equal("0.1235 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s4")); } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -582,35 +514,34 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixForGivenCulture() { var culture = CultureInfo.InvariantCulture; - Assert.Equal("0.1 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s1", culture)); - Assert.Equal("0.12 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s2", culture)); - Assert.Equal("0.123 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s3", culture)); - Assert.Equal("0.1235 g/(kN·s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s4", culture)); + Assert.Equal("0.1 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s1", culture)); + Assert.Equal("0.12 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s2", culture)); + Assert.Equal("0.123 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s3", culture)); + Assert.Equal("0.1235 g/(kN�s)", new SpecificFuelConsumption(0.123456, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificFuelConsumptionUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKiloNewtonSecond(1.0); - Assert.Equal(QuantityType.SpecificFuelConsumption, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs index 6b8e1a3a79..bc9a54aaaa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs @@ -66,12 +66,6 @@ public abstract partial class SpecificVolumeTestsBase : QuantityTestsBase new object[] { SpecificVolumeUnit.MillicubicMeterPerKilogram }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new SpecificVolume((double)0.0, SpecificVolumeUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -80,7 +74,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SpecificVolumeUnit.CubicMeterPerKilogram, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -124,14 +117,9 @@ public void SpecificVolume_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(SpecificVolume.Zero, quantityInfo.Zero); Assert.Equal("SpecificVolume", quantityInfo.Name); - Assert.Equal(QuantityType.SpecificVolume, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SpecificVolumeUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -299,7 +287,7 @@ public void ToUnit(SpecificVolumeUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -316,12 +304,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificVolumeUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificVolumeUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = SpecificVolume.Units.FirstOrDefault(u => u != SpecificVolume.BaseUnit && u != SpecificVolumeUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SpecificVolumeUnit.Undefined) - fromUnit = SpecificVolume.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = SpecificVolume.Units.Where(u => u != SpecificVolume.BaseUnit).DefaultIfEmpty(SpecificVolume.BaseUnit).FirstOrDefault(); var quantity = SpecificVolume.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -399,49 +383,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => cubicmeterperkilogram.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = SpecificVolume.FromCubicMetersPerKilogram(1); - var b = SpecificVolume.FromCubicMetersPerKilogram(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = SpecificVolume.FromCubicMetersPerKilogram(1); - var b = SpecificVolume.FromCubicMetersPerKilogram(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = SpecificVolume.FromCubicMetersPerKilogram(1); - object b = SpecificVolume.FromCubicMetersPerKilogram(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -471,21 +412,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeterperkilogram.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificVolumeUnit.Undefined, SpecificVolume.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast(); foreach(var unit in units) { - if (unit == SpecificVolumeUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -499,8 +431,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 ft³/lb", new SpecificVolume(1, SpecificVolumeUnit.CubicFootPerPound).ToString()); Assert.Equal("1 m³/kg", new SpecificVolume(1, SpecificVolumeUnit.CubicMeterPerKilogram).ToString()); @@ -508,7 +440,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -526,10 +458,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m³/kg", new SpecificVolume(0.123456, SpecificVolumeUnit.CubicMeterPerKilogram).ToString("s1")); Assert.Equal("0.12 m³/kg", new SpecificVolume(0.123456, SpecificVolumeUnit.CubicMeterPerKilogram).ToString("s2")); Assert.Equal("0.123 m³/kg", new SpecificVolume(0.123456, SpecificVolumeUnit.CubicMeterPerKilogram).ToString("s3")); @@ -537,7 +469,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -551,29 +483,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m³/kg", new SpecificVolume(0.123456, SpecificVolumeUnit.CubicMeterPerKilogram).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -693,13 +624,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificVolumeUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(QuantityType.SpecificVolume, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs index 298898a381..6034cab96a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs @@ -122,12 +122,6 @@ public abstract partial class SpecificWeightTestsBase : QuantityTestsBase new object[] { SpecificWeightUnit.TonneForcePerCubicMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new SpecificWeight((double)0.0, SpecificWeightUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -136,7 +130,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SpecificWeightUnit.NewtonPerCubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -180,14 +173,9 @@ public void SpecificWeight_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(SpecificWeight.Zero, quantityInfo.Zero); Assert.Equal("SpecificWeight", quantityInfo.Name); - Assert.Equal(QuantityType.SpecificWeight, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SpecificWeightUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -775,7 +763,7 @@ public void ToUnit(SpecificWeightUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -792,12 +780,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpecificWeightUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificWeightUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = SpecificWeight.Units.FirstOrDefault(u => u != SpecificWeight.BaseUnit && u != SpecificWeightUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SpecificWeightUnit.Undefined) - fromUnit = SpecificWeight.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = SpecificWeight.Units.Where(u => u != SpecificWeight.BaseUnit).DefaultIfEmpty(SpecificWeight.BaseUnit).FirstOrDefault(); var quantity = SpecificWeight.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -889,49 +873,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonpercubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = SpecificWeight.FromNewtonsPerCubicMeter(1); - var b = SpecificWeight.FromNewtonsPerCubicMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = SpecificWeight.FromNewtonsPerCubicMeter(1); - var b = SpecificWeight.FromNewtonsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = SpecificWeight.FromNewtonsPerCubicMeter(1); - object b = SpecificWeight.FromNewtonsPerCubicMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -961,21 +902,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonpercubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpecificWeightUnit.Undefined, SpecificWeight.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SpecificWeightUnit)).Cast(); foreach(var unit in units) { - if (unit == SpecificWeightUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -989,8 +921,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kgf/cm³", new SpecificWeight(1, SpecificWeightUnit.KilogramForcePerCubicCentimeter).ToString()); Assert.Equal("1 kgf/m³", new SpecificWeight(1, SpecificWeightUnit.KilogramForcePerCubicMeter).ToString()); @@ -1012,7 +944,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1044,10 +976,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N/m³", new SpecificWeight(0.123456, SpecificWeightUnit.NewtonPerCubicMeter).ToString("s1")); Assert.Equal("0.12 N/m³", new SpecificWeight(0.123456, SpecificWeightUnit.NewtonPerCubicMeter).ToString("s2")); Assert.Equal("0.123 N/m³", new SpecificWeight(0.123456, SpecificWeightUnit.NewtonPerCubicMeter).ToString("s3")); @@ -1055,7 +987,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1069,29 +1001,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N/m³", new SpecificWeight(0.123456, SpecificWeightUnit.NewtonPerCubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1211,13 +1142,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificWeightUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(QuantityType.SpecificWeight, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs index 25878d3cfb..304c835063 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs @@ -186,12 +186,6 @@ public abstract partial class SpeedTestsBase : QuantityTestsBase new object[] { SpeedUnit.YardPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Speed((double)0.0, SpeedUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -200,7 +194,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(SpeedUnit.MeterPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -244,14 +237,9 @@ public void Speed_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Speed.Zero, quantityInfo.Zero); Assert.Equal("Speed", quantityInfo.Name); - Assert.Equal(QuantityType.Speed, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {SpeedUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2039,7 +2027,7 @@ public void ToUnit(SpeedUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2056,12 +2044,8 @@ public void ToUnit_WithSameUnits_AreEqual(SpeedUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpeedUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Speed.Units.FirstOrDefault(u => u != Speed.BaseUnit && u != SpeedUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == SpeedUnit.Undefined) - fromUnit = Speed.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Speed.Units.Where(u => u != Speed.BaseUnit).DefaultIfEmpty(Speed.BaseUnit).FirstOrDefault(); var quantity = Speed.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -2169,49 +2153,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => meterpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Speed.FromMetersPerSecond(1); - var b = Speed.FromMetersPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Speed.FromMetersPerSecond(1); - var b = Speed.FromMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Speed.FromMetersPerSecond(1); - object b = Speed.FromMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -2241,21 +2182,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(meterpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(SpeedUnit.Undefined, Speed.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(SpeedUnit)).Cast(); foreach(var unit in units) { - if (unit == SpeedUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -2269,8 +2201,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm/h", new Speed(1, SpeedUnit.CentimeterPerHour).ToString()); Assert.Equal("1 cm/min", new Speed(1, SpeedUnit.CentimeterPerMinute).ToString()); @@ -2308,7 +2240,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -2356,10 +2288,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m/s", new Speed(0.123456, SpeedUnit.MeterPerSecond).ToString("s1")); Assert.Equal("0.12 m/s", new Speed(0.123456, SpeedUnit.MeterPerSecond).ToString("s2")); Assert.Equal("0.123 m/s", new Speed(0.123456, SpeedUnit.MeterPerSecond).ToString("s3")); @@ -2367,7 +2299,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -2381,29 +2313,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m/s", new Speed(0.123456, SpeedUnit.MeterPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -2523,13 +2454,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpeedUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(QuantityType.Speed, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs index c9feb407b5..d062d50ecb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs @@ -90,12 +90,6 @@ public abstract partial class StandardVolumeFlowTestsBase : QuantityTestsBase new object[] { StandardVolumeFlowUnit.StandardLiterPerMinute }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new StandardVolumeFlow((double)0.0, StandardVolumeFlowUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -104,7 +98,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -148,14 +141,9 @@ public void StandardVolumeFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(StandardVolumeFlow.Zero, quantityInfo.Zero); Assert.Equal("StandardVolumeFlow", quantityInfo.Name); - Assert.Equal(QuantityType.StandardVolumeFlow, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {StandardVolumeFlowUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -503,7 +491,7 @@ public void ToUnit(StandardVolumeFlowUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -520,12 +508,8 @@ public void ToUnit_WithSameUnits_AreEqual(StandardVolumeFlowUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(StandardVolumeFlowUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = StandardVolumeFlow.Units.FirstOrDefault(u => u != StandardVolumeFlow.BaseUnit && u != StandardVolumeFlowUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == StandardVolumeFlowUnit.Undefined) - fromUnit = StandardVolumeFlow.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = StandardVolumeFlow.Units.Where(u => u != StandardVolumeFlow.BaseUnit).DefaultIfEmpty(StandardVolumeFlow.BaseUnit).FirstOrDefault(); var quantity = StandardVolumeFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -609,49 +593,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => standardcubicmeterpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - var b = StandardVolumeFlow.FromStandardCubicMetersPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - var b = StandardVolumeFlow.FromStandardCubicMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - object b = StandardVolumeFlow.FromStandardCubicMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -681,21 +622,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(standardcubicmeterpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(StandardVolumeFlowUnit.Undefined, StandardVolumeFlow.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(StandardVolumeFlowUnit)).Cast(); foreach(var unit in units) { - if (unit == StandardVolumeFlowUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -709,8 +641,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 sccm", new StandardVolumeFlow(1, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute).ToString()); Assert.Equal("1 scfh", new StandardVolumeFlow(1, StandardVolumeFlowUnit.StandardCubicFootPerHour).ToString()); @@ -724,7 +656,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -748,10 +680,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 Sm³/s", new StandardVolumeFlow(0.123456, StandardVolumeFlowUnit.StandardCubicMeterPerSecond).ToString("s1")); Assert.Equal("0.12 Sm³/s", new StandardVolumeFlow(0.123456, StandardVolumeFlowUnit.StandardCubicMeterPerSecond).ToString("s2")); Assert.Equal("0.123 Sm³/s", new StandardVolumeFlow(0.123456, StandardVolumeFlowUnit.StandardCubicMeterPerSecond).ToString("s3")); @@ -759,7 +691,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -773,29 +705,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 Sm³/s", new StandardVolumeFlow(0.123456, StandardVolumeFlowUnit.StandardCubicMeterPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -915,13 +846,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(StandardVolumeFlowUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(QuantityType.StandardVolumeFlow, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs index 3e3155a036..d8487f7950 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs @@ -94,12 +94,6 @@ public abstract partial class TemperatureChangeRateTestsBase : QuantityTestsBase new object[] { TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new TemperatureChangeRate((double)0.0, TemperatureChangeRateUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -108,7 +102,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -152,14 +145,9 @@ public void TemperatureChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuan Assert.Equal(TemperatureChangeRate.Zero, quantityInfo.Zero); Assert.Equal("TemperatureChangeRate", quantityInfo.Name); - Assert.Equal(QuantityType.TemperatureChangeRate, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TemperatureChangeRateUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -537,7 +525,7 @@ public void ToUnit(TemperatureChangeRateUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -554,12 +542,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureChangeRateUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureChangeRateUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = TemperatureChangeRate.Units.FirstOrDefault(u => u != TemperatureChangeRate.BaseUnit && u != TemperatureChangeRateUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TemperatureChangeRateUnit.Undefined) - fromUnit = TemperatureChangeRate.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = TemperatureChangeRate.Units.Where(u => u != TemperatureChangeRate.BaseUnit).DefaultIfEmpty(TemperatureChangeRate.BaseUnit).FirstOrDefault(); var quantity = TemperatureChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -644,49 +628,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => degreecelsiuspersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - var b = TemperatureChangeRate.FromDegreesCelsiusPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - var b = TemperatureChangeRate.FromDegreesCelsiusPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - object b = TemperatureChangeRate.FromDegreesCelsiusPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -716,21 +657,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(degreecelsiuspersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureChangeRateUnit.Undefined, TemperatureChangeRate.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast(); foreach(var unit in units) { - if (unit == TemperatureChangeRateUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -744,8 +676,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 c°C/s", new TemperatureChangeRate(1, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond).ToString()); Assert.Equal("1 da°C/s", new TemperatureChangeRate(1, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond).ToString()); @@ -760,7 +692,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -785,10 +717,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 °C/s", new TemperatureChangeRate(0.123456, TemperatureChangeRateUnit.DegreeCelsiusPerSecond).ToString("s1")); Assert.Equal("0.12 °C/s", new TemperatureChangeRate(0.123456, TemperatureChangeRateUnit.DegreeCelsiusPerSecond).ToString("s2")); Assert.Equal("0.123 °C/s", new TemperatureChangeRate(0.123456, TemperatureChangeRateUnit.DegreeCelsiusPerSecond).ToString("s3")); @@ -796,7 +728,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -810,29 +742,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 °C/s", new TemperatureChangeRate(0.123456, TemperatureChangeRateUnit.DegreeCelsiusPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -952,13 +883,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureChangeRateUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(QuantityType.TemperatureChangeRate, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs index 55314159f1..efea864547 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs @@ -90,12 +90,6 @@ public abstract partial class TemperatureDeltaTestsBase : QuantityTestsBase new object[] { TemperatureDeltaUnit.MillidegreeCelsius }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new TemperatureDelta((double)0.0, TemperatureDeltaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -104,7 +98,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TemperatureDeltaUnit.Kelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -148,14 +141,9 @@ public void TemperatureDelta_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(TemperatureDelta.Zero, quantityInfo.Zero); Assert.Equal("TemperatureDelta", quantityInfo.Name); - Assert.Equal(QuantityType.TemperatureDelta, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TemperatureDeltaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -503,7 +491,7 @@ public void ToUnit(TemperatureDeltaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -520,12 +508,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureDeltaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureDeltaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = TemperatureDelta.Units.FirstOrDefault(u => u != TemperatureDelta.BaseUnit && u != TemperatureDeltaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TemperatureDeltaUnit.Undefined) - fromUnit = TemperatureDelta.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = TemperatureDelta.Units.Where(u => u != TemperatureDelta.BaseUnit).DefaultIfEmpty(TemperatureDelta.BaseUnit).FirstOrDefault(); var quantity = TemperatureDelta.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -609,49 +593,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = TemperatureDelta.FromKelvins(1); - var b = TemperatureDelta.FromKelvins(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = TemperatureDelta.FromKelvins(1); - var b = TemperatureDelta.FromKelvins(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = TemperatureDelta.FromKelvins(1); - object b = TemperatureDelta.FromKelvins(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -681,21 +622,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureDeltaUnit.Undefined, TemperatureDelta.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast(); foreach(var unit in units) { - if (unit == TemperatureDeltaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -709,8 +641,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 ∆°C", new TemperatureDelta(1, TemperatureDeltaUnit.DegreeCelsius).ToString()); Assert.Equal("1 ∆°De", new TemperatureDelta(1, TemperatureDeltaUnit.DegreeDelisle).ToString()); @@ -724,7 +656,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -748,10 +680,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 ∆K", new TemperatureDelta(0.123456, TemperatureDeltaUnit.Kelvin).ToString("s1")); Assert.Equal("0.12 ∆K", new TemperatureDelta(0.123456, TemperatureDeltaUnit.Kelvin).ToString("s2")); Assert.Equal("0.123 ∆K", new TemperatureDelta(0.123456, TemperatureDeltaUnit.Kelvin).ToString("s3")); @@ -759,7 +691,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -773,29 +705,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 ∆K", new TemperatureDelta(0.123456, TemperatureDeltaUnit.Kelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -915,13 +846,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureDeltaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(QuantityType.TemperatureDelta, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs index a7bd601c9f..f93e60b571 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs @@ -70,12 +70,6 @@ public abstract partial class TemperatureGradientTestsBase : QuantityTestsBase new object[] { TemperatureGradientUnit.KelvinPerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new TemperatureGradient((double)0.0, TemperatureGradientUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -84,7 +78,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TemperatureGradientUnit.KelvinPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -128,14 +121,9 @@ public void TemperatureGradient_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(TemperatureGradient.Zero, quantityInfo.Zero); Assert.Equal("TemperatureGradient", quantityInfo.Name); - Assert.Equal(QuantityType.TemperatureGradient, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TemperatureGradientUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -333,7 +321,7 @@ public void ToUnit(TemperatureGradientUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -350,12 +338,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureGradientUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureGradientUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = TemperatureGradient.Units.FirstOrDefault(u => u != TemperatureGradient.BaseUnit && u != TemperatureGradientUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TemperatureGradientUnit.Undefined) - fromUnit = TemperatureGradient.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = TemperatureGradient.Units.Where(u => u != TemperatureGradient.BaseUnit).DefaultIfEmpty(TemperatureGradient.BaseUnit).FirstOrDefault(); var quantity = TemperatureGradient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -434,49 +418,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kelvinpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = TemperatureGradient.FromKelvinsPerMeter(1); - var b = TemperatureGradient.FromKelvinsPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = TemperatureGradient.FromKelvinsPerMeter(1); - var b = TemperatureGradient.FromKelvinsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = TemperatureGradient.FromKelvinsPerMeter(1); - object b = TemperatureGradient.FromKelvinsPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -506,21 +447,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kelvinpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureGradientUnit.Undefined, TemperatureGradient.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TemperatureGradientUnit)).Cast(); foreach(var unit in units) { - if (unit == TemperatureGradientUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -534,8 +466,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 ∆°C/km", new TemperatureGradient(1, TemperatureGradientUnit.DegreeCelsiusPerKilometer).ToString()); Assert.Equal("1 ∆°C/m", new TemperatureGradient(1, TemperatureGradientUnit.DegreeCelsiusPerMeter).ToString()); @@ -544,7 +476,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -563,10 +495,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 ∆°K/m", new TemperatureGradient(0.123456, TemperatureGradientUnit.KelvinPerMeter).ToString("s1")); Assert.Equal("0.12 ∆°K/m", new TemperatureGradient(0.123456, TemperatureGradientUnit.KelvinPerMeter).ToString("s2")); Assert.Equal("0.123 ∆°K/m", new TemperatureGradient(0.123456, TemperatureGradientUnit.KelvinPerMeter).ToString("s3")); @@ -574,7 +506,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -588,29 +520,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 ∆°K/m", new TemperatureGradient(0.123456, TemperatureGradientUnit.KelvinPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -730,13 +661,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureGradientUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(QuantityType.TemperatureGradient, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs index 6040427ab3..e1bd752656 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs @@ -94,12 +94,6 @@ public abstract partial class TemperatureTestsBase : QuantityTestsBase new object[] { TemperatureUnit.SolarTemperature }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Temperature((double)0.0, TemperatureUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -108,7 +102,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TemperatureUnit.Kelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -152,14 +145,9 @@ public void Temperature_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Temperature.Zero, quantityInfo.Zero); Assert.Equal("Temperature", quantityInfo.Name); - Assert.Equal(QuantityType.Temperature, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TemperatureUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -537,7 +525,7 @@ public void ToUnit(TemperatureUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -554,12 +542,8 @@ public void ToUnit_WithSameUnits_AreEqual(TemperatureUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Temperature.Units.FirstOrDefault(u => u != Temperature.BaseUnit && u != TemperatureUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TemperatureUnit.Undefined) - fromUnit = Temperature.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Temperature.Units.Where(u => u != Temperature.BaseUnit).DefaultIfEmpty(Temperature.BaseUnit).FirstOrDefault(); var quantity = Temperature.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -632,49 +616,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => kelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Temperature.FromKelvins(1); - var b = Temperature.FromKelvins(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Temperature.FromKelvins(1); - var b = Temperature.FromKelvins(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Temperature.FromKelvins(1); - object b = Temperature.FromKelvins(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -704,21 +645,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(kelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TemperatureUnit.Undefined, Temperature.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TemperatureUnit)).Cast(); foreach(var unit in units) { - if (unit == TemperatureUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -732,8 +664,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 °C", new Temperature(1, TemperatureUnit.DegreeCelsius).ToString()); Assert.Equal("1 °De", new Temperature(1, TemperatureUnit.DegreeDelisle).ToString()); @@ -748,7 +680,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -773,10 +705,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 K", new Temperature(0.123456, TemperatureUnit.Kelvin).ToString("s1")); Assert.Equal("0.12 K", new Temperature(0.123456, TemperatureUnit.Kelvin).ToString("s2")); Assert.Equal("0.123 K", new Temperature(0.123456, TemperatureUnit.Kelvin).ToString("s3")); @@ -784,7 +716,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -798,29 +730,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 K", new Temperature(0.123456, TemperatureUnit.Kelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Temperature.FromKelvins(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -940,13 +871,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(QuantityType.Temperature, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs index 1052f620b9..85422d9414 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs @@ -62,12 +62,6 @@ public abstract partial class ThermalConductivityTestsBase : QuantityTestsBase new object[] { ThermalConductivityUnit.WattPerMeterKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ThermalConductivity((double)0.0, ThermalConductivityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -76,7 +70,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ThermalConductivityUnit.WattPerMeterKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -120,14 +113,9 @@ public void ThermalConductivity_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(ThermalConductivity.Zero, quantityInfo.Zero); Assert.Equal("ThermalConductivity", quantityInfo.Name); - Assert.Equal(QuantityType.ThermalConductivity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ThermalConductivityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -265,7 +253,7 @@ public void ToUnit(ThermalConductivityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -282,12 +270,8 @@ public void ToUnit_WithSameUnits_AreEqual(ThermalConductivityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalConductivityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ThermalConductivity.Units.FirstOrDefault(u => u != ThermalConductivity.BaseUnit && u != ThermalConductivityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ThermalConductivityUnit.Undefined) - fromUnit = ThermalConductivity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ThermalConductivity.Units.Where(u => u != ThermalConductivity.BaseUnit).DefaultIfEmpty(ThermalConductivity.BaseUnit).FirstOrDefault(); var quantity = ThermalConductivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -364,49 +348,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => wattpermeterkelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ThermalConductivity.FromWattsPerMeterKelvin(1); - var b = ThermalConductivity.FromWattsPerMeterKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ThermalConductivity.FromWattsPerMeterKelvin(1); - var b = ThermalConductivity.FromWattsPerMeterKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ThermalConductivity.FromWattsPerMeterKelvin(1); - object b = ThermalConductivity.FromWattsPerMeterKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -436,21 +377,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpermeterkelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ThermalConductivityUnit.Undefined, ThermalConductivity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast(); foreach(var unit in units) { - if (unit == ThermalConductivityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -464,15 +396,15 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 BTU/h·ft·°F", new ThermalConductivity(1, ThermalConductivityUnit.BtuPerHourFootFahrenheit).ToString()); Assert.Equal("1 W/m·K", new ThermalConductivity(1, ThermalConductivityUnit.WattPerMeterKelvin).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -489,10 +421,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 W/m·K", new ThermalConductivity(0.123456, ThermalConductivityUnit.WattPerMeterKelvin).ToString("s1")); Assert.Equal("0.12 W/m·K", new ThermalConductivity(0.123456, ThermalConductivityUnit.WattPerMeterKelvin).ToString("s2")); Assert.Equal("0.123 W/m·K", new ThermalConductivity(0.123456, ThermalConductivityUnit.WattPerMeterKelvin).ToString("s3")); @@ -500,7 +432,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -514,29 +446,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 W/m·K", new ThermalConductivity(0.123456, ThermalConductivityUnit.WattPerMeterKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -656,13 +587,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ThermalConductivityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(QuantityType.ThermalConductivity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs index 33a7c93724..9ad3c2e04c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class ThermalResistanceTestsBase : QuantityTestsBase new object[] { ThermalResistanceUnit.SquareMeterKelvinPerWatt }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new ThermalResistance((double)0.0, ThermalResistanceUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void ThermalResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(ThermalResistance.Zero, quantityInfo.Zero); Assert.Equal("ThermalResistance", quantityInfo.Name); - Assert.Equal(QuantityType.ThermalResistance, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {ThermalResistanceUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -401,7 +389,7 @@ public void ToUnit(ThermalResistanceUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -418,12 +406,8 @@ public void ToUnit_WithSameUnits_AreEqual(ThermalResistanceUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalResistanceUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = ThermalResistance.Units.FirstOrDefault(u => u != ThermalResistance.BaseUnit && u != ThermalResistanceUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == ThermalResistanceUnit.Undefined) - fromUnit = ThermalResistance.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = ThermalResistance.Units.Where(u => u != ThermalResistance.BaseUnit).DefaultIfEmpty(ThermalResistance.BaseUnit).FirstOrDefault(); var quantity = ThermalResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -504,49 +488,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => squaremeterkelvinperkilowatt.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - var b = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - var b = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1); - object b = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -576,21 +517,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(squaremeterkelvinperkilowatt.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(ThermalResistanceUnit.Undefined, ThermalResistance.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast(); foreach(var unit in units) { - if (unit == ThermalResistanceUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -604,8 +536,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 Hrft²°F/Btu", new ThermalResistance(1, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu).ToString()); Assert.Equal("1 cm²Hr°C/kcal", new ThermalResistance(1, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie).ToString()); @@ -616,7 +548,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -637,10 +569,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m²K/kW", new ThermalResistance(0.123456, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt).ToString("s1")); Assert.Equal("0.12 m²K/kW", new ThermalResistance(0.123456, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt).ToString("s2")); Assert.Equal("0.123 m²K/kW", new ThermalResistance(0.123456, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt).ToString("s3")); @@ -648,7 +580,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -662,29 +594,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m²K/kW", new ThermalResistance(0.123456, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -804,13 +735,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ThermalResistanceUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = ThermalResistance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(QuantityType.ThermalResistance, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs index 23faf4a50a..18d63aa0f7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorquePerLengthTestsBase.g.cs @@ -138,12 +138,6 @@ public abstract partial class TorquePerLengthTestsBase : QuantityTestsBase new object[] { TorquePerLengthUnit.TonneForceMillimeterPerMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new TorquePerLength((double)0.0, TorquePerLengthUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -152,7 +146,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TorquePerLengthUnit.NewtonMeterPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -196,14 +189,9 @@ public void TorquePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(TorquePerLength.Zero, quantityInfo.Zero); Assert.Equal("TorquePerLength", quantityInfo.Name); - Assert.Equal(QuantityType.TorquePerLength, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TorquePerLengthUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -983,7 +971,7 @@ public void ToUnit(TorquePerLengthUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1000,12 +988,8 @@ public void ToUnit_WithSameUnits_AreEqual(TorquePerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorquePerLengthUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = TorquePerLength.Units.FirstOrDefault(u => u != TorquePerLength.BaseUnit && u != TorquePerLengthUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TorquePerLengthUnit.Undefined) - fromUnit = TorquePerLength.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = TorquePerLength.Units.Where(u => u != TorquePerLength.BaseUnit).DefaultIfEmpty(TorquePerLength.BaseUnit).FirstOrDefault(); var quantity = TorquePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1101,49 +1085,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonmeterpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = TorquePerLength.FromNewtonMetersPerMeter(1); - var b = TorquePerLength.FromNewtonMetersPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = TorquePerLength.FromNewtonMetersPerMeter(1); - var b = TorquePerLength.FromNewtonMetersPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = TorquePerLength.FromNewtonMetersPerMeter(1); - object b = TorquePerLength.FromNewtonMetersPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1173,21 +1114,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonmeterpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TorquePerLengthUnit.Undefined, TorquePerLength.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TorquePerLengthUnit)).Cast(); foreach(var unit in units) { - if (unit == TorquePerLengthUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1201,8 +1133,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 kgf·cm/m", new TorquePerLength(1, TorquePerLengthUnit.KilogramForceCentimeterPerMeter).ToString()); Assert.Equal("1 kgf·m/m", new TorquePerLength(1, TorquePerLengthUnit.KilogramForceMeterPerMeter).ToString()); @@ -1228,7 +1160,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1264,10 +1196,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N·m/m", new TorquePerLength(0.123456, TorquePerLengthUnit.NewtonMeterPerMeter).ToString("s1")); Assert.Equal("0.12 N·m/m", new TorquePerLength(0.123456, TorquePerLengthUnit.NewtonMeterPerMeter).ToString("s2")); Assert.Equal("0.123 N·m/m", new TorquePerLength(0.123456, TorquePerLengthUnit.NewtonMeterPerMeter).ToString("s3")); @@ -1275,7 +1207,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1289,29 +1221,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N·m/m", new TorquePerLength(0.123456, TorquePerLengthUnit.NewtonMeterPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1431,13 +1362,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TorquePerLengthUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = TorquePerLength.FromNewtonMetersPerMeter(1.0); - Assert.Equal(QuantityType.TorquePerLength, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs index 144fc52a32..71b8792c7b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs @@ -154,12 +154,6 @@ public abstract partial class TorqueTestsBase : QuantityTestsBase new object[] { TorqueUnit.TonneForceMillimeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Torque((double)0.0, TorqueUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -168,7 +162,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TorqueUnit.NewtonMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -212,14 +205,9 @@ public void Torque_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Torque.Zero, quantityInfo.Zero); Assert.Equal("Torque", quantityInfo.Name); - Assert.Equal(QuantityType.Torque, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TorqueUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -1119,7 +1107,7 @@ public void ToUnit(TorqueUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -1136,12 +1124,8 @@ public void ToUnit_WithSameUnits_AreEqual(TorqueUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorqueUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Torque.Units.FirstOrDefault(u => u != Torque.BaseUnit && u != TorqueUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TorqueUnit.Undefined) - fromUnit = Torque.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Torque.Units.Where(u => u != Torque.BaseUnit).DefaultIfEmpty(Torque.BaseUnit).FirstOrDefault(); var quantity = Torque.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1241,49 +1225,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => newtonmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Torque.FromNewtonMeters(1); - var b = Torque.FromNewtonMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Torque.FromNewtonMeters(1); - var b = Torque.FromNewtonMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Torque.FromNewtonMeters(1); - object b = Torque.FromNewtonMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1313,21 +1254,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TorqueUnit.Undefined, Torque.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TorqueUnit)).Cast(); foreach(var unit in units) { - if (unit == TorqueUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1341,8 +1273,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 gf·cm", new Torque(1, TorqueUnit.GramForceCentimeter).ToString()); Assert.Equal("1 gf·m", new Torque(1, TorqueUnit.GramForceMeter).ToString()); @@ -1372,7 +1304,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1412,10 +1344,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 N·m", new Torque(0.123456, TorqueUnit.NewtonMeter).ToString("s1")); Assert.Equal("0.12 N·m", new Torque(0.123456, TorqueUnit.NewtonMeter).ToString("s2")); Assert.Equal("0.123 N·m", new Torque(0.123456, TorqueUnit.NewtonMeter).ToString("s3")); @@ -1423,7 +1355,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1437,29 +1369,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 N·m", new Torque(0.123456, TorqueUnit.NewtonMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Torque.FromNewtonMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1579,13 +1510,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TorqueUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(QuantityType.Torque, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs index 2bb8fd0912..88a0ef4fac 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class TurbidityTestsBase : QuantityTestsBase new object[] { TurbidityUnit.NTU }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Turbidity((double)0.0, TurbidityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(TurbidityUnit.NTU, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void Turbidity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Turbidity.Zero, quantityInfo.Zero); Assert.Equal("Turbidity", quantityInfo.Name); - Assert.Equal(QuantityType.Turbidity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {TurbidityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(TurbidityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(TurbidityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TurbidityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Turbidity.Units.FirstOrDefault(u => u != Turbidity.BaseUnit && u != TurbidityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == TurbidityUnit.Undefined) - fromUnit = Turbidity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Turbidity.Units.Where(u => u != Turbidity.BaseUnit).DefaultIfEmpty(Turbidity.BaseUnit).FirstOrDefault(); var quantity = Turbidity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => ntu.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Turbidity.FromNTU(1); - var b = Turbidity.FromNTU(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Turbidity.FromNTU(1); - var b = Turbidity.FromNTU(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Turbidity.FromNTU(1); - object b = Turbidity.FromNTU(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(ntu.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(TurbidityUnit.Undefined, Turbidity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(TurbidityUnit)).Cast(); foreach(var unit in units) { - if (unit == TurbidityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 NTU", new Turbidity(1, TurbidityUnit.NTU).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 NTU", new Turbidity(0.123456, TurbidityUnit.NTU).ToString("s1")); Assert.Equal("0.12 NTU", new Turbidity(0.123456, TurbidityUnit.NTU).ToString("s2")); Assert.Equal("0.123 NTU", new Turbidity(0.123456, TurbidityUnit.NTU).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 NTU", new Turbidity(0.123456, TurbidityUnit.NTU).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Turbidity.FromNTU(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TurbidityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(QuantityType.Turbidity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs index a215a17706..4a746cf648 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs @@ -58,12 +58,6 @@ public abstract partial class VitaminATestsBase : QuantityTestsBase new object[] { VitaminAUnit.InternationalUnit }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new VitaminA((double)0.0, VitaminAUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -72,7 +66,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VitaminAUnit.InternationalUnit, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -116,14 +109,9 @@ public void VitaminA_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(VitaminA.Zero, quantityInfo.Zero); Assert.Equal("VitaminA", quantityInfo.Name); - Assert.Equal(QuantityType.VitaminA, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VitaminAUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -231,7 +219,7 @@ public void ToUnit(VitaminAUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -248,12 +236,8 @@ public void ToUnit_WithSameUnits_AreEqual(VitaminAUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VitaminAUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = VitaminA.Units.FirstOrDefault(u => u != VitaminA.BaseUnit && u != VitaminAUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VitaminAUnit.Undefined) - fromUnit = VitaminA.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = VitaminA.Units.Where(u => u != VitaminA.BaseUnit).DefaultIfEmpty(VitaminA.BaseUnit).FirstOrDefault(); var quantity = VitaminA.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -329,49 +313,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => internationalunit.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = VitaminA.FromInternationalUnits(1); - var b = VitaminA.FromInternationalUnits(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = VitaminA.FromInternationalUnits(1); - var b = VitaminA.FromInternationalUnits(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = VitaminA.FromInternationalUnits(1); - object b = VitaminA.FromInternationalUnits(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -401,21 +342,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(internationalunit.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VitaminAUnit.Undefined, VitaminA.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VitaminAUnit)).Cast(); foreach(var unit in units) { - if (unit == VitaminAUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -429,14 +361,14 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 IU", new VitaminA(1, VitaminAUnit.InternationalUnit).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -452,10 +384,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 IU", new VitaminA(0.123456, VitaminAUnit.InternationalUnit).ToString("s1")); Assert.Equal("0.12 IU", new VitaminA(0.123456, VitaminAUnit.InternationalUnit).ToString("s2")); Assert.Equal("0.123 IU", new VitaminA(0.123456, VitaminAUnit.InternationalUnit).ToString("s3")); @@ -463,7 +395,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -477,29 +409,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 IU", new VitaminA(0.123456, VitaminAUnit.InternationalUnit).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -619,13 +550,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VitaminAUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(QuantityType.VitaminA, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs index 30c75b077c..492e55dd98 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs @@ -134,12 +134,6 @@ public abstract partial class VolumeConcentrationTestsBase : QuantityTestsBase new object[] { VolumeConcentrationUnit.PicolitersPerMililiter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new VolumeConcentration((double)0.0, VolumeConcentrationUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -148,7 +142,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VolumeConcentrationUnit.DecimalFraction, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -192,14 +185,9 @@ public void VolumeConcentration_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(VolumeConcentration.Zero, quantityInfo.Zero); Assert.Equal("VolumeConcentration", quantityInfo.Name); - Assert.Equal(QuantityType.VolumeConcentration, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VolumeConcentrationUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -901,7 +889,7 @@ public void ToUnit(VolumeConcentrationUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -918,12 +906,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeConcentrationUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeConcentrationUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = VolumeConcentration.Units.FirstOrDefault(u => u != VolumeConcentration.BaseUnit && u != VolumeConcentrationUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VolumeConcentrationUnit.Undefined) - fromUnit = VolumeConcentration.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = VolumeConcentration.Units.Where(u => u != VolumeConcentration.BaseUnit).DefaultIfEmpty(VolumeConcentration.BaseUnit).FirstOrDefault(); var quantity = VolumeConcentration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -1018,49 +1002,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => decimalfraction.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = VolumeConcentration.FromDecimalFractions(1); - var b = VolumeConcentration.FromDecimalFractions(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = VolumeConcentration.FromDecimalFractions(1); - var b = VolumeConcentration.FromDecimalFractions(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = VolumeConcentration.FromDecimalFractions(1); - object b = VolumeConcentration.FromDecimalFractions(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -1090,21 +1031,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(decimalfraction.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumeConcentrationUnit.Undefined, VolumeConcentration.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VolumeConcentrationUnit)).Cast(); foreach(var unit in units) { - if (unit == VolumeConcentrationUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -1118,8 +1050,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cL/L", new VolumeConcentration(1, VolumeConcentrationUnit.CentilitersPerLiter).ToString()); Assert.Equal("1 cL/mL", new VolumeConcentration(1, VolumeConcentrationUnit.CentilitersPerMililiter).ToString()); @@ -1144,7 +1076,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -1179,10 +1111,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1", new VolumeConcentration(0.123456, VolumeConcentrationUnit.DecimalFraction).ToString("s1")); Assert.Equal("0.12", new VolumeConcentration(0.123456, VolumeConcentrationUnit.DecimalFraction).ToString("s2")); Assert.Equal("0.123", new VolumeConcentration(0.123456, VolumeConcentrationUnit.DecimalFraction).ToString("s3")); @@ -1190,7 +1122,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -1204,29 +1136,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235", new VolumeConcentration(0.123456, VolumeConcentrationUnit.DecimalFraction).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -1346,13 +1277,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeConcentrationUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(QuantityType.VolumeConcentration, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs index 75676cea80..5f69823e6b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs @@ -62,12 +62,6 @@ public abstract partial class VolumeFlowPerAreaTestsBase : QuantityTestsBase new object[] { VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new VolumeFlowPerArea((double)0.0, VolumeFlowPerAreaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -76,7 +70,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -120,14 +113,9 @@ public void VolumeFlowPerArea_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(VolumeFlowPerArea.Zero, quantityInfo.Zero); Assert.Equal("VolumeFlowPerArea", quantityInfo.Name); - Assert.Equal(QuantityType.VolumeFlowPerArea, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VolumeFlowPerAreaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -265,7 +253,7 @@ public void ToUnit(VolumeFlowPerAreaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -282,12 +270,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeFlowPerAreaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowPerAreaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = VolumeFlowPerArea.Units.FirstOrDefault(u => u != VolumeFlowPerArea.BaseUnit && u != VolumeFlowPerAreaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VolumeFlowPerAreaUnit.Undefined) - fromUnit = VolumeFlowPerArea.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = VolumeFlowPerArea.Units.Where(u => u != VolumeFlowPerArea.BaseUnit).DefaultIfEmpty(VolumeFlowPerArea.BaseUnit).FirstOrDefault(); var quantity = VolumeFlowPerArea.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -364,49 +348,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => cubicmeterpersecondpersquaremeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - var b = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - var b = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - object b = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -436,21 +377,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeterpersecondpersquaremeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumeFlowPerAreaUnit.Undefined, VolumeFlowPerArea.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VolumeFlowPerAreaUnit)).Cast(); foreach(var unit in units) { - if (unit == VolumeFlowPerAreaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -464,15 +396,15 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 CFM/ft²", new VolumeFlowPerArea(1, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot).ToString()); Assert.Equal("1 m³/(s·m²)", new VolumeFlowPerArea(1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter).ToString()); } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -489,10 +421,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m³/(s·m²)", new VolumeFlowPerArea(0.123456, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter).ToString("s1")); Assert.Equal("0.12 m³/(s·m²)", new VolumeFlowPerArea(0.123456, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter).ToString("s2")); Assert.Equal("0.123 m³/(s·m²)", new VolumeFlowPerArea(0.123456, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter).ToString("s3")); @@ -500,7 +432,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -514,29 +446,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m³/(s·m²)", new VolumeFlowPerArea(0.123456, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -656,13 +587,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeFlowPerAreaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(QuantityType.VolumeFlowPerArea, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs index b569a0c95f..9411da6a26 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs @@ -215,7 +215,7 @@ public abstract partial class VolumeFlowTestsBase : QuantityTestsBase VolumeFlowUnit.MilliliterPerHour => (MillilitersPerHourInOneCubicMeterPerSecond, MillilitersPerHourTolerance), VolumeFlowUnit.MilliliterPerMinute => (MillilitersPerMinuteInOneCubicMeterPerSecond, MillilitersPerMinuteTolerance), VolumeFlowUnit.MilliliterPerSecond => (MillilitersPerSecondInOneCubicMeterPerSecond, MillilitersPerSecondTolerance), - VolumeFlowUnit.MillionUsGallonsPerDay => (MillionUsGallonsPerDayInOneCubicMeterPerSecond, MillionUsGallonsPerDayTolerance), + VolumeFlowUnit.MillionUsGallonPerDay => (MillionUsGallonsPerDayInOneCubicMeterPerSecond, MillionUsGallonsPerDayTolerance), VolumeFlowUnit.NanoliterPerDay => (NanolitersPerDayInOneCubicMeterPerSecond, NanolitersPerDayTolerance), VolumeFlowUnit.NanoliterPerHour => (NanolitersPerHourInOneCubicMeterPerSecond, NanolitersPerHourTolerance), VolumeFlowUnit.NanoliterPerMinute => (NanolitersPerMinuteInOneCubicMeterPerSecond, NanolitersPerMinuteTolerance), @@ -283,7 +283,7 @@ public abstract partial class VolumeFlowTestsBase : QuantityTestsBase new object[] { VolumeFlowUnit.MilliliterPerHour }, new object[] { VolumeFlowUnit.MilliliterPerMinute }, new object[] { VolumeFlowUnit.MilliliterPerSecond }, - new object[] { VolumeFlowUnit.MillionUsGallonsPerDay }, + new object[] { VolumeFlowUnit.MillionUsGallonPerDay }, new object[] { VolumeFlowUnit.NanoliterPerDay }, new object[] { VolumeFlowUnit.NanoliterPerHour }, new object[] { VolumeFlowUnit.NanoliterPerMinute }, @@ -302,12 +302,6 @@ public abstract partial class VolumeFlowTestsBase : QuantityTestsBase new object[] { VolumeFlowUnit.UsGallonPerSecond }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new VolumeFlow((double)0.0, VolumeFlowUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -316,7 +310,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -360,14 +353,9 @@ public void VolumeFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(VolumeFlow.Zero, quantityInfo.Zero); Assert.Equal("VolumeFlow", quantityInfo.Name); - Assert.Equal(QuantityType.VolumeFlow, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VolumeFlowUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -621,9 +609,9 @@ public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() AssertEx.EqualTolerance(1, quantity44.MillilitersPerSecond, MillilitersPerSecondTolerance); Assert.Equal(VolumeFlowUnit.MilliliterPerSecond, quantity44.Unit); - var quantity45 = VolumeFlow.From(1, VolumeFlowUnit.MillionUsGallonsPerDay); + var quantity45 = VolumeFlow.From(1, VolumeFlowUnit.MillionUsGallonPerDay); AssertEx.EqualTolerance(1, quantity45.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, quantity45.Unit); + Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, quantity45.Unit); var quantity46 = VolumeFlow.From(1, VolumeFlowUnit.NanoliterPerDay); AssertEx.EqualTolerance(1, quantity46.NanolitersPerDay, NanolitersPerDayTolerance); @@ -753,7 +741,7 @@ public void As() AssertEx.EqualTolerance(MillilitersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MilliliterPerHour), MillilitersPerHourTolerance); AssertEx.EqualTolerance(MillilitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MilliliterPerMinute), MillilitersPerMinuteTolerance); AssertEx.EqualTolerance(MillilitersPerSecondInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MilliliterPerSecond), MillilitersPerSecondTolerance); - AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MillionUsGallonsPerDay), MillionUsGallonsPerDayTolerance); + AssertEx.EqualTolerance(MillionUsGallonsPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.MillionUsGallonPerDay), MillionUsGallonsPerDayTolerance); AssertEx.EqualTolerance(NanolitersPerDayInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.NanoliterPerDay), NanolitersPerDayTolerance); AssertEx.EqualTolerance(NanolitersPerHourInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.NanoliterPerHour), NanolitersPerHourTolerance); AssertEx.EqualTolerance(NanolitersPerMinuteInOneCubicMeterPerSecond, cubicmeterpersecond.As(VolumeFlowUnit.NanoliterPerMinute), NanolitersPerMinuteTolerance); @@ -1524,7 +1512,7 @@ public void Parse() { var parsed = VolumeFlow.Parse("1 MGD", CultureInfo.GetCultureInfo("en-US")); AssertEx.EqualTolerance(1, parsed.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, parsed.Unit); + Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, parsed.Unit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } try @@ -2326,7 +2314,7 @@ public void TryParse() { Assert.True(VolumeFlow.TryParse("1 MGD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); AssertEx.EqualTolerance(1, parsed.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, parsed.Unit); + Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, parsed.Unit); } { @@ -3135,7 +3123,7 @@ public void ParseUnit() try { var parsedUnit = VolumeFlow.ParseUnit("MGD", CultureInfo.GetCultureInfo("en-US")); - Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, parsedUnit); + Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, parsedUnit); } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } try @@ -3809,7 +3797,7 @@ public void TryParseUnit() { Assert.True(VolumeFlow.TryParseUnit("MGD", CultureInfo.GetCultureInfo("en-US"), out var parsedUnit)); - Assert.Equal(VolumeFlowUnit.MillionUsGallonsPerDay, parsedUnit); + Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, parsedUnit); } { @@ -3967,7 +3955,7 @@ public void ToUnit(VolumeFlowUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -3984,12 +3972,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeFlowUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = VolumeFlow.Units.FirstOrDefault(u => u != VolumeFlow.BaseUnit && u != VolumeFlowUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VolumeFlowUnit.Undefined) - fromUnit = VolumeFlow.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = VolumeFlow.Units.Where(u => u != VolumeFlow.BaseUnit).DefaultIfEmpty(VolumeFlow.BaseUnit).FirstOrDefault(); var quantity = VolumeFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -4126,49 +4110,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => cubicmeterpersecond.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = VolumeFlow.FromCubicMetersPerSecond(1); - var b = VolumeFlow.FromCubicMetersPerSecond(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = VolumeFlow.FromCubicMetersPerSecond(1); - var b = VolumeFlow.FromCubicMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = VolumeFlow.FromCubicMetersPerSecond(1); - object b = VolumeFlow.FromCubicMetersPerSecond(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -4198,21 +4139,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeterpersecond.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumeFlowUnit.Undefined, VolumeFlow.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VolumeFlowUnit)).Cast(); foreach(var unit in units) { - if (unit == VolumeFlowUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -4226,8 +4158,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 af/d", new VolumeFlow(1, VolumeFlowUnit.AcreFootPerDay).ToString()); Assert.Equal("1 af/h", new VolumeFlow(1, VolumeFlowUnit.AcreFootPerHour).ToString()); @@ -4274,7 +4206,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() Assert.Equal("1 mL/h", new VolumeFlow(1, VolumeFlowUnit.MilliliterPerHour).ToString()); Assert.Equal("1 mL/min", new VolumeFlow(1, VolumeFlowUnit.MilliliterPerMinute).ToString()); Assert.Equal("1 mL/s", new VolumeFlow(1, VolumeFlowUnit.MilliliterPerSecond).ToString()); - Assert.Equal("1 MGD", new VolumeFlow(1, VolumeFlowUnit.MillionUsGallonsPerDay).ToString()); + Assert.Equal("1 MGD", new VolumeFlow(1, VolumeFlowUnit.MillionUsGallonPerDay).ToString()); Assert.Equal("1 nl/day", new VolumeFlow(1, VolumeFlowUnit.NanoliterPerDay).ToString()); Assert.Equal("1 nL/h", new VolumeFlow(1, VolumeFlowUnit.NanoliterPerHour).ToString()); Assert.Equal("1 nL/min", new VolumeFlow(1, VolumeFlowUnit.NanoliterPerMinute).ToString()); @@ -4294,7 +4226,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -4349,7 +4281,7 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture Assert.Equal("1 mL/h", new VolumeFlow(1, VolumeFlowUnit.MilliliterPerHour).ToString(swedishCulture)); Assert.Equal("1 mL/min", new VolumeFlow(1, VolumeFlowUnit.MilliliterPerMinute).ToString(swedishCulture)); Assert.Equal("1 mL/s", new VolumeFlow(1, VolumeFlowUnit.MilliliterPerSecond).ToString(swedishCulture)); - Assert.Equal("1 MGD", new VolumeFlow(1, VolumeFlowUnit.MillionUsGallonsPerDay).ToString(swedishCulture)); + Assert.Equal("1 MGD", new VolumeFlow(1, VolumeFlowUnit.MillionUsGallonPerDay).ToString(swedishCulture)); Assert.Equal("1 nl/day", new VolumeFlow(1, VolumeFlowUnit.NanoliterPerDay).ToString(swedishCulture)); Assert.Equal("1 nL/h", new VolumeFlow(1, VolumeFlowUnit.NanoliterPerHour).ToString(swedishCulture)); Assert.Equal("1 nL/min", new VolumeFlow(1, VolumeFlowUnit.NanoliterPerMinute).ToString(swedishCulture)); @@ -4371,10 +4303,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m³/s", new VolumeFlow(0.123456, VolumeFlowUnit.CubicMeterPerSecond).ToString("s1")); Assert.Equal("0.12 m³/s", new VolumeFlow(0.123456, VolumeFlowUnit.CubicMeterPerSecond).ToString("s2")); Assert.Equal("0.123 m³/s", new VolumeFlow(0.123456, VolumeFlowUnit.CubicMeterPerSecond).ToString("s3")); @@ -4382,7 +4314,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -4396,29 +4328,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m³/s", new VolumeFlow(0.123456, VolumeFlowUnit.CubicMeterPerSecond).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -4538,13 +4469,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeFlowUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(QuantityType.VolumeFlow, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs index 8d9fe9e2cc..bb9be87224 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs @@ -82,12 +82,6 @@ public abstract partial class VolumePerLengthTestsBase : QuantityTestsBase new object[] { VolumePerLengthUnit.OilBarrelPerFoot }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new VolumePerLength((double)0.0, VolumePerLengthUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -96,7 +90,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VolumePerLengthUnit.CubicMeterPerMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -140,14 +133,9 @@ public void VolumePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(VolumePerLength.Zero, quantityInfo.Zero); Assert.Equal("VolumePerLength", quantityInfo.Name); - Assert.Equal(QuantityType.VolumePerLength, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VolumePerLengthUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -435,7 +423,7 @@ public void ToUnit(VolumePerLengthUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -452,12 +440,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumePerLengthUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumePerLengthUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = VolumePerLength.Units.FirstOrDefault(u => u != VolumePerLength.BaseUnit && u != VolumePerLengthUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VolumePerLengthUnit.Undefined) - fromUnit = VolumePerLength.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = VolumePerLength.Units.Where(u => u != VolumePerLength.BaseUnit).DefaultIfEmpty(VolumePerLength.BaseUnit).FirstOrDefault(); var quantity = VolumePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -539,49 +523,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => cubicmeterpermeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = VolumePerLength.FromCubicMetersPerMeter(1); - var b = VolumePerLength.FromCubicMetersPerMeter(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = VolumePerLength.FromCubicMetersPerMeter(1); - var b = VolumePerLength.FromCubicMetersPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = VolumePerLength.FromCubicMetersPerMeter(1); - object b = VolumePerLength.FromCubicMetersPerMeter(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -611,21 +552,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeterpermeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumePerLengthUnit.Undefined, VolumePerLength.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VolumePerLengthUnit)).Cast(); foreach(var unit in units) { - if (unit == VolumePerLengthUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -639,8 +571,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 m³/m", new VolumePerLength(1, VolumePerLengthUnit.CubicMeterPerMeter).ToString()); Assert.Equal("1 yd³/ft", new VolumePerLength(1, VolumePerLengthUnit.CubicYardPerFoot).ToString()); @@ -652,7 +584,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -674,10 +606,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m³/m", new VolumePerLength(0.123456, VolumePerLengthUnit.CubicMeterPerMeter).ToString("s1")); Assert.Equal("0.12 m³/m", new VolumePerLength(0.123456, VolumePerLengthUnit.CubicMeterPerMeter).ToString("s2")); Assert.Equal("0.123 m³/m", new VolumePerLength(0.123456, VolumePerLengthUnit.CubicMeterPerMeter).ToString("s3")); @@ -685,7 +617,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -699,29 +631,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m³/m", new VolumePerLength(0.123456, VolumePerLengthUnit.CubicMeterPerMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -841,13 +772,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumePerLengthUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(QuantityType.VolumePerLength, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs index e72df280e4..39e9f8781a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs @@ -262,12 +262,6 @@ public abstract partial class VolumeTestsBase : QuantityTestsBase new object[] { VolumeUnit.UsTeaspoon }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new Volume((double)0.0, VolumeUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -276,7 +270,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VolumeUnit.CubicMeter, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -320,14 +313,9 @@ public void Volume_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(Volume.Zero, quantityInfo.Zero); Assert.Equal("Volume", quantityInfo.Name); - Assert.Equal(QuantityType.Volume, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VolumeUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -2961,7 +2949,7 @@ public void ToUnit(VolumeUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -2978,12 +2966,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumeUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = Volume.Units.FirstOrDefault(u => u != Volume.BaseUnit && u != VolumeUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VolumeUnit.Undefined) - fromUnit = Volume.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = Volume.Units.Where(u => u != Volume.BaseUnit).DefaultIfEmpty(Volume.BaseUnit).FirstOrDefault(); var quantity = Volume.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -3110,49 +3094,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => cubicmeter.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = Volume.FromCubicMeters(1); - var b = Volume.FromCubicMeters(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = Volume.FromCubicMeters(1); - var b = Volume.FromCubicMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = Volume.FromCubicMeters(1); - object b = Volume.FromCubicMeters(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -3182,21 +3123,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeter.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumeUnit.Undefined, Volume.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VolumeUnit)).Cast(); foreach(var unit in units) { - if (unit == VolumeUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -3210,8 +3142,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 ac-ft", new Volume(1, VolumeUnit.AcreFoot).ToString()); Assert.Equal("1", new Volume(1, VolumeUnit.AuTablespoon).ToString()); @@ -3268,7 +3200,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -3335,10 +3267,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m³", new Volume(0.123456, VolumeUnit.CubicMeter).ToString("s1")); Assert.Equal("0.12 m³", new Volume(0.123456, VolumeUnit.CubicMeter).ToString("s2")); Assert.Equal("0.123 m³", new Volume(0.123456, VolumeUnit.CubicMeter).ToString("s3")); @@ -3346,7 +3278,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -3360,29 +3292,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m³", new Volume(0.123456, VolumeUnit.CubicMeter).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = Volume.FromCubicMeters(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -3502,13 +3433,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(QuantityType.Volume, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs index d538f340ee..8f1651ee0c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs @@ -90,12 +90,6 @@ public abstract partial class VolumetricHeatCapacityTestsBase : QuantityTestsBas new object[] { VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new VolumetricHeatCapacity((double)0.0, VolumetricHeatCapacityUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -104,7 +98,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -148,14 +141,9 @@ public void VolumetricHeatCapacity_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(VolumetricHeatCapacity.Zero, quantityInfo.Zero); Assert.Equal("VolumetricHeatCapacity", quantityInfo.Name); - Assert.Equal(QuantityType.VolumetricHeatCapacity, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {VolumetricHeatCapacityUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -503,7 +491,7 @@ public void ToUnit(VolumetricHeatCapacityUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -520,12 +508,8 @@ public void ToUnit_WithSameUnits_AreEqual(VolumetricHeatCapacityUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumetricHeatCapacityUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = VolumetricHeatCapacity.Units.FirstOrDefault(u => u != VolumetricHeatCapacity.BaseUnit && u != VolumetricHeatCapacityUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == VolumetricHeatCapacityUnit.Undefined) - fromUnit = VolumetricHeatCapacity.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = VolumetricHeatCapacity.Units.Where(u => u != VolumetricHeatCapacity.BaseUnit).DefaultIfEmpty(VolumetricHeatCapacity.BaseUnit).FirstOrDefault(); var quantity = VolumetricHeatCapacity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -609,49 +593,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => joulepercubicmeterkelvin.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - var b = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - var b = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - object b = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -681,21 +622,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(joulepercubicmeterkelvin.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(VolumetricHeatCapacityUnit.Undefined, VolumetricHeatCapacity.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(VolumetricHeatCapacityUnit)).Cast(); foreach(var unit in units) { - if (unit == VolumetricHeatCapacityUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -709,8 +641,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 BTU/ft³·°F", new VolumetricHeatCapacity(1, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit).ToString()); Assert.Equal("1 cal/cm³·°C", new VolumetricHeatCapacity(1, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius).ToString()); @@ -724,7 +656,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -748,10 +680,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 J/m³·K", new VolumetricHeatCapacity(0.123456, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin).ToString("s1")); Assert.Equal("0.12 J/m³·K", new VolumetricHeatCapacity(0.123456, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin).ToString("s2")); Assert.Equal("0.123 J/m³·K", new VolumetricHeatCapacity(0.123456, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin).ToString("s3")); @@ -759,7 +691,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -773,29 +705,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 J/m³·K", new VolumetricHeatCapacity(0.123456, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -915,13 +846,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumetricHeatCapacityUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(QuantityType.VolumetricHeatCapacity, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs index 5fb089fdc6..23f866287a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs @@ -78,12 +78,6 @@ public abstract partial class WarpingMomentOfInertiaTestsBase : QuantityTestsBas new object[] { WarpingMomentOfInertiaUnit.MillimeterToTheSixth }, }; - [Fact] - public void Ctor_WithUndefinedUnit_ThrowsArgumentException() - { - Assert.Throws(() => new WarpingMomentOfInertia((double)0.0, WarpingMomentOfInertiaUnit.Undefined)); - } - [Fact] public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() { @@ -92,7 +86,6 @@ public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() Assert.Equal(WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity.Unit); } - [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() { @@ -136,14 +129,9 @@ public void WarpingMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(WarpingMomentOfInertia.Zero, quantityInfo.Zero); Assert.Equal("WarpingMomentOfInertia", quantityInfo.Name); - Assert.Equal(QuantityType.WarpingMomentOfInertia, quantityInfo.QuantityType); - var units = EnumUtils.GetEnumValues().Except(new[] {WarpingMomentOfInertiaUnit.Undefined}).OrderBy(x => x.ToString()).ToArray(); + var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var unitNames = units.Select(x => x.ToString()); - - // Obsolete members - Assert.Equal(units, quantityInfo.Units); - Assert.Equal(unitNames, quantityInfo.UnitNames); } [Fact] @@ -545,7 +533,7 @@ public void ToUnit(WarpingMomentOfInertiaUnit unit) var converted = inBaseUnits.ToUnit(unit); var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence); + AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); Assert.Equal(unit, converted.Unit); } @@ -562,12 +550,8 @@ public void ToUnit_WithSameUnits_AreEqual(WarpingMomentOfInertiaUnit unit) [MemberData(nameof(UnitTypes))] public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(WarpingMomentOfInertiaUnit unit) { - // See if there is a unit available that is not the base unit. - var fromUnit = WarpingMomentOfInertia.Units.FirstOrDefault(u => u != WarpingMomentOfInertia.BaseUnit && u != WarpingMomentOfInertiaUnit.Undefined); - - // If there is only one unit for the quantity, we must use the base unit. - if (fromUnit == WarpingMomentOfInertiaUnit.Undefined) - fromUnit = WarpingMomentOfInertia.BaseUnit; + // See if there is a unit available that is not the base unit, fallback to base unit if it has only a single unit. + var fromUnit = WarpingMomentOfInertia.Units.Where(u => u != WarpingMomentOfInertia.BaseUnit).DefaultIfEmpty(WarpingMomentOfInertia.BaseUnit).FirstOrDefault(); var quantity = WarpingMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); @@ -648,49 +632,6 @@ public void CompareToThrowsOnNull() Assert.Throws(() => metertothesixth.CompareTo(null)); } - [Fact] - public void EqualityOperators() - { - var a = WarpingMomentOfInertia.FromMetersToTheSixth(1); - var b = WarpingMomentOfInertia.FromMetersToTheSixth(2); - -#pragma warning disable CS8073 -// ReSharper disable EqualExpressionComparison - - Assert.True(a == a); - Assert.False(a != a); - - Assert.True(a != b); - Assert.False(a == b); - - Assert.False(a == null); - Assert.False(null == a); - -// ReSharper restore EqualExpressionComparison -#pragma warning restore CS8073 - } - - [Fact] - public void Equals_SameType_IsImplemented() - { - var a = WarpingMomentOfInertia.FromMetersToTheSixth(1); - var b = WarpingMomentOfInertia.FromMetersToTheSixth(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - } - - [Fact] - public void Equals_QuantityAsObject_IsImplemented() - { - object a = WarpingMomentOfInertia.FromMetersToTheSixth(1); - object b = WarpingMomentOfInertia.FromMetersToTheSixth(2); - - Assert.True(a.Equals(a)); - Assert.False(a.Equals(b)); - Assert.False(a.Equals((object)null)); - } - [Fact] public void Equals_RelativeTolerance_IsImplemented() { @@ -720,21 +661,12 @@ public void EqualsReturnsFalseOnNull() Assert.False(metertothesixth.Equals(null)); } - [Fact] - public void UnitsDoesNotContainUndefined() - { - Assert.DoesNotContain(WarpingMomentOfInertiaUnit.Undefined, WarpingMomentOfInertia.Units); - } - [Fact] public void HasAtLeastOneAbbreviationSpecified() { var units = Enum.GetValues(typeof(WarpingMomentOfInertiaUnit)).Cast(); foreach(var unit in units) { - if (unit == WarpingMomentOfInertiaUnit.Undefined) - continue; - var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit); } } @@ -748,8 +680,8 @@ public void BaseDimensionsShouldNeverBeNull() [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { - var prevCulture = Thread.CurrentThread.CurrentUICulture; - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + var prevCulture = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { Assert.Equal("1 cm⁶", new WarpingMomentOfInertia(1, WarpingMomentOfInertiaUnit.CentimeterToTheSixth).ToString()); Assert.Equal("1 dm⁶", new WarpingMomentOfInertia(1, WarpingMomentOfInertiaUnit.DecimeterToTheSixth).ToString()); @@ -760,7 +692,7 @@ public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() } finally { - Thread.CurrentThread.CurrentUICulture = prevCulture; + Thread.CurrentThread.CurrentCulture = prevCulture; } } @@ -781,10 +713,10 @@ public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCulture [Fact] public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.1 m⁶", new WarpingMomentOfInertia(0.123456, WarpingMomentOfInertiaUnit.MeterToTheSixth).ToString("s1")); Assert.Equal("0.12 m⁶", new WarpingMomentOfInertia(0.123456, WarpingMomentOfInertiaUnit.MeterToTheSixth).ToString("s2")); Assert.Equal("0.123 m⁶", new WarpingMomentOfInertia(0.123456, WarpingMomentOfInertiaUnit.MeterToTheSixth).ToString("s3")); @@ -792,7 +724,7 @@ public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCul } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } @@ -806,29 +738,28 @@ public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixFor Assert.Equal("0.1235 m⁶", new WarpingMomentOfInertia(0.123456, WarpingMomentOfInertiaUnit.MeterToTheSixth).ToString("s4", culture)); } - - [Fact] - public void ToString_NullFormat_ThrowsArgumentNullException() + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) { var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Throws(() => quantity.ToString(null, null, null)); - } + CultureInfo formatProvider = cultureName == null + ? null + : CultureInfo.GetCultureInfo(cultureName); - [Fact] - public void ToString_NullArgs_ThrowsArgumentNullException() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Throws(() => quantity.ToString(null, "g", null)); + Assert.Equal(quantity.ToString("g", formatProvider), quantity.ToString(null, formatProvider)); } - [Fact] - public void ToString_NullProvider_EqualsCurrentUICulture() + [Theory] + [InlineData(null)] + [InlineData("g")] + public void ToString_NullProvider_EqualsCurrentCulture(string format) { var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, "g"), quantity.ToString(null, "g")); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] public void Convert_ToBool_ThrowsInvalidCastException() { @@ -948,13 +879,6 @@ public void Convert_ChangeType_UnitType_EqualsUnit() Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(WarpingMomentOfInertiaUnit))); } - [Fact] - public void Convert_ChangeType_QuantityType_EqualsQuantityType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(QuantityType.WarpingMomentOfInertia, Convert.ChangeType(quantity, typeof(QuantityType))); - } - [Fact] public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() { diff --git a/UnitsNet.Tests/IntOverloadTests.cs b/UnitsNet.Tests/IntOverloadTests.cs index bf63007ba7..9d059dcc46 100644 --- a/UnitsNet.Tests/IntOverloadTests.cs +++ b/UnitsNet.Tests/IntOverloadTests.cs @@ -18,7 +18,7 @@ public static void CreatingQuantityWithDoubleBackingFieldFromIntReturnsCorrectVa public static void CreatingQuantityWithIntBackingFieldFromIntReturnsCorrectValue() { Power power = Power.FromWatts(1); - Assert.Equal(1.0, power.Watts); + Assert.Equal(1.0m, power.Watts); } } } diff --git a/UnitsNet.Tests/LongOverloadTests.cs b/UnitsNet.Tests/LongOverloadTests.cs index fd54377f08..ba5c00a538 100644 --- a/UnitsNet.Tests/LongOverloadTests.cs +++ b/UnitsNet.Tests/LongOverloadTests.cs @@ -18,7 +18,7 @@ public static void CreatingQuantityWithDoubleBackingFieldFromLongReturnsCorrectV public static void CreatingQuantityWithLongBackingFieldFromLongReturnsCorrectValue() { Power power = Power.FromWatts(1L); - Assert.Equal(1.0, power.Watts); + Assert.Equal(1.0m, power.Watts); } } } diff --git a/UnitsNet.Tests/QuantityFormatterTests.cs b/UnitsNet.Tests/QuantityFormatterTests.cs index 1a4d2315eb..06628d5b44 100644 --- a/UnitsNet.Tests/QuantityFormatterTests.cs +++ b/UnitsNet.Tests/QuantityFormatterTests.cs @@ -109,10 +109,19 @@ public static void StandardNumericFormatStrings_Equals_ValueWithFormatStringAndA { var length = Length.FromMeters(123456789.987654321); - var expected = string.Format(CultureInfo.CurrentUICulture, $"{{0:{format}}} {{1:a}}", length.Value, length); + var expected = string.Format(CultureInfo.CurrentCulture, $"{{0:{format}}} {{1:a}}", length.Value, length); Assert.Equal(expected, QuantityFormatter.Format(length, format)); } + [Fact] + public static void StandardNumericFormatStringsAsPartOfLongerFormatStringsWork() + { + var length = Length.FromMeters(123.321); + var expected = "The distance is 123.3 m"; + var actual = $"The distance is {length.ToString("F1", CultureInfo.InvariantCulture)}"; + Assert.Equal(expected, actual); + } + [Theory] [InlineData("000")] [InlineData("0.00")] @@ -133,7 +142,7 @@ public static void CustomNumericFormatStrings_Equals_ValueWithFormatStringAndAbb { var length = Length.FromMeters(123456789.987654321); - var expected = string.Format(CultureInfo.CurrentUICulture, $"{{0:{format}}} {{1:a}}", length.Value, length); + var expected = string.Format(CultureInfo.CurrentCulture, $"{{0:{format}}} {{1:a}}", length.Value, length); Assert.Equal(expected, QuantityFormatter.Format(length, format)); } } diff --git a/UnitsNet.Tests/QuantityIConvertibleTests.cs b/UnitsNet.Tests/QuantityIConvertibleTests.cs index 5c5f7983a5..a5949444c9 100644 --- a/UnitsNet.Tests/QuantityIConvertibleTests.cs +++ b/UnitsNet.Tests/QuantityIConvertibleTests.cs @@ -7,178 +7,174 @@ namespace UnitsNet.Tests { public class QuantityIConvertibleTests { - private static Length length = Length.FromMeters(3.0); - private static IConvertible lengthAsIConvertible = Length.FromMeters(3.0); + private static Length _length = Length.FromMeters(3.0); + private static readonly IConvertible LengthAsIConvertible = Length.FromMeters(3.0); [Fact] public void GetTypeCodeTest() { - Assert.Equal(TypeCode.Object, lengthAsIConvertible.GetTypeCode()); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(length)); + Assert.Equal(TypeCode.Object, LengthAsIConvertible.GetTypeCode()); + Assert.Equal(TypeCode.Object, Convert.GetTypeCode(_length)); } [Fact] public void ToBooleanTest() { - Assert.Throws(() => lengthAsIConvertible.ToBoolean(null)); - Assert.Throws(() => Convert.ToBoolean(length)); - Assert.Throws(() => Convert.ChangeType(length, typeof(bool))); + Assert.Throws(() => LengthAsIConvertible.ToBoolean(null)); + Assert.Throws(() => Convert.ToBoolean(_length)); + Assert.Throws(() => Convert.ChangeType(_length, typeof(bool))); } [Fact] public void ToByteTest() { byte expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToByte(null)); - Assert.Equal(expected, Convert.ToByte(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(byte))); + Assert.Equal(expected, LengthAsIConvertible.ToByte(null)); + Assert.Equal(expected, Convert.ToByte(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(byte))); } [Fact] public void ToCharTest() { - Assert.Throws(() => lengthAsIConvertible.ToChar(null)); - Assert.Throws(() => Convert.ToChar(length)); - Assert.Throws(() => Convert.ChangeType(length, typeof(char))); + Assert.Throws(() => LengthAsIConvertible.ToChar(null)); + Assert.Throws(() => Convert.ToChar(_length)); + Assert.Throws(() => Convert.ChangeType(_length, typeof(char))); } [Fact] public void ToDateTimeTest() { - Assert.Throws(() => lengthAsIConvertible.ToDateTime(null)); - Assert.Throws(() => Convert.ToDateTime(length)); - Assert.Throws(() => Convert.ChangeType(length, typeof(DateTime))); + Assert.Throws(() => LengthAsIConvertible.ToDateTime(null)); + Assert.Throws(() => Convert.ToDateTime(_length)); + Assert.Throws(() => Convert.ChangeType(_length, typeof(DateTime))); } [Fact] public void ToDecimalTest() { decimal expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToDecimal(null)); - Assert.Equal(expected, Convert.ToDecimal(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(decimal))); + Assert.Equal(expected, LengthAsIConvertible.ToDecimal(null)); + Assert.Equal(expected, Convert.ToDecimal(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(decimal))); } [Fact] public void ToDoubleTest() { double expected = 3.0; - Assert.Equal(expected, lengthAsIConvertible.ToDouble(null)); - Assert.Equal(expected, Convert.ToDouble(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(double))); + Assert.Equal(expected, LengthAsIConvertible.ToDouble(null)); + Assert.Equal(expected, Convert.ToDouble(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(double))); } [Fact] public void ToInt16Test() { short expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToInt16(null)); - Assert.Equal(expected, Convert.ToInt16(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(short))); + Assert.Equal(expected, LengthAsIConvertible.ToInt16(null)); + Assert.Equal(expected, Convert.ToInt16(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(short))); } [Fact] public void ToInt32Test() { int expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToInt32(null)); - Assert.Equal(expected, Convert.ToInt32(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(int))); + Assert.Equal(expected, LengthAsIConvertible.ToInt32(null)); + Assert.Equal(expected, Convert.ToInt32(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(int))); } [Fact] public void ToInt64Test() { long expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToInt64(null)); - Assert.Equal(expected, Convert.ToInt64(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(long))); + Assert.Equal(expected, LengthAsIConvertible.ToInt64(null)); + Assert.Equal(expected, Convert.ToInt64(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(long))); } [Fact] public void ToSByteTest() { sbyte expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToSByte(null)); - Assert.Equal(expected, Convert.ToSByte(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(sbyte))); + Assert.Equal(expected, LengthAsIConvertible.ToSByte(null)); + Assert.Equal(expected, Convert.ToSByte(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(sbyte))); } [Fact] public void ToSingleTest() { float expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToSingle(null)); - Assert.Equal(expected, Convert.ToSingle(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(float))); + Assert.Equal(expected, LengthAsIConvertible.ToSingle(null)); + Assert.Equal(expected, Convert.ToSingle(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(float))); } [Fact] public void ToStringTest() { - string expected = length.ToString(CultureInfo.CurrentUICulture); - Assert.Equal(expected, lengthAsIConvertible.ToString(CultureInfo.CurrentUICulture)); - Assert.Equal(expected, Convert.ToString(length, CultureInfo.CurrentUICulture)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(string), CultureInfo.CurrentUICulture)); + string expected = _length.ToString(CultureInfo.CurrentCulture); + Assert.Equal(expected, LengthAsIConvertible.ToString(CultureInfo.CurrentCulture)); + Assert.Equal(expected, Convert.ToString(_length, CultureInfo.CurrentCulture)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(string), CultureInfo.CurrentCulture)); } [Fact] public void ToTypeTest() { // Same quantity type - Assert.Equal(length, lengthAsIConvertible.ToType(typeof(Length), null)); - Assert.Equal(length, Convert.ChangeType(length, typeof(Length))); + Assert.Equal(_length, LengthAsIConvertible.ToType(typeof(Length), null)); + Assert.Equal(_length, Convert.ChangeType(_length, typeof(Length))); // Same unit type - Assert.Equal(length.Unit, lengthAsIConvertible.ToType(typeof(LengthUnit), null)); - Assert.Equal(length.Unit, Convert.ChangeType(length, typeof(LengthUnit))); + Assert.Equal(_length.Unit, LengthAsIConvertible.ToType(typeof(LengthUnit), null)); + Assert.Equal(_length.Unit, Convert.ChangeType(_length, typeof(LengthUnit))); // Different type - Assert.Throws(() => lengthAsIConvertible.ToType(typeof(Duration), null)); - Assert.Throws(() => Convert.ChangeType(length, typeof(Duration))); + Assert.Throws(() => LengthAsIConvertible.ToType(typeof(Duration), null)); + Assert.Throws(() => Convert.ChangeType(_length, typeof(Duration))); // Different unit type - Assert.Throws(() => lengthAsIConvertible.ToType(typeof(DurationUnit), null)); - Assert.Throws(() => Convert.ChangeType(length, typeof(DurationUnit))); - - // QuantityType - Assert.Equal(Length.QuantityType, lengthAsIConvertible.ToType(typeof(QuantityType), null)); - Assert.Equal(Length.QuantityType, Convert.ChangeType(length, typeof(QuantityType))); + Assert.Throws(() => LengthAsIConvertible.ToType(typeof(DurationUnit), null)); + Assert.Throws(() => Convert.ChangeType(_length, typeof(DurationUnit))); // QuantityInfo - Assert.Equal(Length.Info, lengthAsIConvertible.ToType(typeof(QuantityInfo), null)); - Assert.Equal(Length.Info, Convert.ChangeType(length, typeof(QuantityInfo))); + Assert.Equal(Length.Info, LengthAsIConvertible.ToType(typeof(QuantityInfo), null)); + Assert.Equal(Length.Info, Convert.ChangeType(_length, typeof(QuantityInfo))); // BaseDimensions - Assert.Equal(Length.BaseDimensions, lengthAsIConvertible.ToType(typeof(BaseDimensions), null)); - Assert.Equal(Length.BaseDimensions, Convert.ChangeType(length, typeof(BaseDimensions))); + Assert.Equal(Length.BaseDimensions, LengthAsIConvertible.ToType(typeof(BaseDimensions), null)); + Assert.Equal(Length.BaseDimensions, Convert.ChangeType(_length, typeof(BaseDimensions))); } [Fact] public void ToUInt16Test() { ushort expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToUInt16(null)); - Assert.Equal(expected, Convert.ToUInt16(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(ushort))); + Assert.Equal(expected, LengthAsIConvertible.ToUInt16(null)); + Assert.Equal(expected, Convert.ToUInt16(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(ushort))); } [Fact] public void ToUInt32Test() { uint expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToUInt32(null)); - Assert.Equal(expected, Convert.ToUInt32(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(uint))); + Assert.Equal(expected, LengthAsIConvertible.ToUInt32(null)); + Assert.Equal(expected, Convert.ToUInt32(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(uint))); } [Fact] public void ToUInt64Test() { ulong expected = 3; - Assert.Equal(expected, lengthAsIConvertible.ToUInt64(null)); - Assert.Equal(expected, Convert.ToUInt64(length)); - Assert.Equal(expected, Convert.ChangeType(length, typeof(ulong))); + Assert.Equal(expected, LengthAsIConvertible.ToUInt64(null)); + Assert.Equal(expected, Convert.ToUInt64(_length)); + Assert.Equal(expected, Convert.ChangeType(_length, typeof(ulong))); } } } diff --git a/UnitsNet.Tests/QuantityIFormattableTests.cs b/UnitsNet.Tests/QuantityIFormattableTests.cs index 059b5b22e2..e6ebbfcad0 100644 --- a/UnitsNet.Tests/QuantityIFormattableTests.cs +++ b/UnitsNet.Tests/QuantityIFormattableTests.cs @@ -40,31 +40,12 @@ public void AFormatWithInvalidIndexThrowsFormatException() Assert.Throws(() => length.ToString("a100")); } - [Fact] - public void VFormatEqualsValueToString() - { - Assert.Equal(length.Value.ToString(CultureInfo.CurrentUICulture), length.ToString("v")); - } - [Fact] public void QFormatEqualsQuantityName() { Assert.Equal(Length.Info.Name, length.ToString("q")); } - [Theory] - [InlineData("s", "1 ft")] - [InlineData("s1", "1.2 ft")] - [InlineData("s2", "1.23 ft")] - [InlineData("s3", "1.235 ft")] - [InlineData("s4", "1.2346 ft")] - [InlineData("s5", "1.23457 ft")] - [InlineData("s6", "1.234568 ft")] - public void SFormatEqualsSignificantDigits(string sFormatString, string expected) - { - Assert.Equal(expected, length.ToString(sFormatString, NumberFormatInfo.InvariantInfo)); - } - [Fact] public void UFormatEqualsUnitToString() { diff --git a/UnitsNet.Tests/QuantityInfoTest.cs b/UnitsNet.Tests/QuantityInfoTest.cs index f3cbdea055..bdaab3dca9 100644 --- a/UnitsNet.Tests/QuantityInfoTest.cs +++ b/UnitsNet.Tests/QuantityInfoTest.cs @@ -3,7 +3,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using UnitsNet.Tests.CustomQuantities; using UnitsNet.Units; using Xunit; @@ -16,40 +15,32 @@ public class QuantityInfoTest public void Constructor_AssignsProperties() { var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new UnitInfo[]{ - new UnitInfo(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), - new UnitInfo(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer)) + UnitInfo[] expectedUnitInfos = { + new(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), + new(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer)) }; var expectedBaseUnit = LengthUnit.Centimeter; - var expectedQuantityType = QuantityType.Length; var expectedBaseDimensions = Length.BaseDimensions; var info = new QuantityInfo(nameof(Length), typeof(LengthUnit), expectedUnitInfos, - expectedBaseUnit, expectedZero, expectedBaseDimensions, QuantityType.Length); + expectedBaseUnit, expectedZero, expectedBaseDimensions); Assert.Equal(expectedZero, info.Zero); Assert.Equal("Length", info.Name); Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedQuantityType, info.QuantityType); Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - - // Obsolete members - Assert.Equal( expectedBaseUnit, info.BaseUnit ); - Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); } [Fact] public void Constructor_AssignsPropertiesForCustomQuantity() { var expectedZero = new HowMuch(10, HowMuchUnit.Some); - var expectedUnitInfos = new UnitInfo[] - { - new UnitInfo(HowMuchUnit.Some, "Some", BaseUnits.Undefined), - new UnitInfo(HowMuchUnit.ATon, "Tons", BaseUnits.Undefined), - new UnitInfo(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined) + UnitInfo[] expectedUnitInfos = { + new(HowMuchUnit.Some, "Some", BaseUnits.Undefined), + new(HowMuchUnit.ATon, "Tons", BaseUnits.Undefined), + new(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined) }; var expectedBaseUnit = HowMuchUnit.Some; - var expectedQuantityType = QuantityType.Undefined; var expectedBaseDimensions = BaseDimensions.Dimensionless; var info = new QuantityInfo(nameof(HowMuch), typeof(HowMuchUnit), expectedUnitInfos, @@ -58,63 +49,25 @@ public void Constructor_AssignsPropertiesForCustomQuantity() Assert.Equal(expectedZero, info.Zero); Assert.Equal(nameof(HowMuch), info.Name); Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedQuantityType, info.QuantityType); - Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - - // Obsolete members - Assert.Equal( expectedBaseUnit, info.BaseUnit ); - Assert.Equal(new[] {nameof(HowMuchUnit.Some), nameof(HowMuchUnit.ATon), nameof(HowMuchUnit.AShitTon)}, info.UnitNames); - } - - [Fact] - public void ObsoleteConstructor_AssignsProperties() - { - var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new UnitInfo[]{ - new UnitInfo(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), - new UnitInfo(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer)) - }; - var expectedBaseUnit = LengthUnit.Centimeter; - var expectedQuantityType = QuantityType.Length; - var expectedBaseDimensions = Length.BaseDimensions; - - var info = new QuantityInfo(QuantityType.Length, expectedUnitInfos, expectedBaseUnit, expectedZero, expectedBaseDimensions); - - Assert.Equal(expectedZero, info.Zero); - Assert.Equal("Length", info.Name); - Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedQuantityType, info.QuantityType); Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - - // Obsolete members - Assert.Equal( expectedBaseUnit, info.BaseUnit ); - Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); } - [Fact] public void GenericsConstructor_AssignsProperties() { var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new UnitInfo[]{ - new UnitInfo(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), - new UnitInfo(LengthUnit.Kilometer,"Kilometers", new BaseUnits(LengthUnit.Kilometer)) + UnitInfo[] expectedUnitInfos = { + new(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), + new(LengthUnit.Kilometer,"Kilometers", new BaseUnits(LengthUnit.Kilometer)) }; var expectedBaseUnit = LengthUnit.Centimeter; - var expectedQuantityType = QuantityType.Length; var expectedBaseDimensions = Length.BaseDimensions; - var info = new QuantityInfo(nameof(Length), expectedUnitInfos, - expectedBaseUnit, expectedZero, expectedBaseDimensions, expectedQuantityType); + var info = new QuantityInfo(nameof(Length), expectedUnitInfos, expectedBaseUnit, expectedZero, expectedBaseDimensions); Assert.Equal(expectedZero, info.Zero); Assert.Equal("Length", info.Name); Assert.Equal(expectedUnitInfos, info.UnitInfos); Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - - // Obsolete members - Assert.Equal(expectedQuantityType, info.QuantityType); - Assert.Equal( expectedBaseUnit, info.BaseUnit ); - Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); } [Fact] @@ -122,7 +75,7 @@ public void GenericsConstructor_AssignsProperties() public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - null, Length.BaseUnit, Length.Zero, Length.BaseDimensions, QuantityType.Length)); + null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] @@ -130,7 +83,7 @@ public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() public void GenericsConstructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), - null, Length.BaseUnit, Length.Zero, Length.BaseDimensions, QuantityType.Length)); + null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] @@ -138,7 +91,7 @@ public void GenericsConstructor_GivenNullAsUnitInfos_ThrowsArgumentNullException public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - Length.Info.UnitInfos, null, Length.Zero, Length.BaseDimensions, QuantityType.Length)); + Length.Info.UnitInfos, null, Length.Zero, Length.BaseDimensions)); } [Fact] @@ -146,7 +99,7 @@ public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions, QuantityType.Length)); + Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); } [Fact] @@ -154,7 +107,7 @@ public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), - Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions, QuantityType.Length)); + Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); } [Fact] @@ -162,7 +115,7 @@ public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null, QuantityType.Length)); + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); } [Fact] @@ -170,7 +123,7 @@ public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() public void GenericsConstructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(nameof(Length), - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null, QuantityType.Length)); + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); } [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] @@ -247,9 +200,10 @@ public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperat var baseUnits = new BaseUnits(LengthUnit.Meter); var quantityInfo = new QuantityInfo(Length.Info.Name, - new UnitInfo[]{ - new UnitInfo(LengthUnit.Meter, "Meters", baseUnits), - new UnitInfo(LengthUnit.Foot, "Feet", baseUnits) }, + new UnitInfo[] { + new(LengthUnit.Meter, "Meters", baseUnits), + new(LengthUnit.Foot, "Feet", baseUnits) + }, LengthUnit.Meter, Length.Zero, Length.BaseDimensions); Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnits)); @@ -258,7 +212,7 @@ public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperat [Fact] public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() { - Assert.Throws(() => Length.Info.GetUnitInfosFor(null)); + Assert.Throws(() => Length.Info.GetUnitInfosFor(null!)); } [Fact] @@ -283,9 +237,9 @@ public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMat var baseUnits = new BaseUnits(LengthUnit.Meter); var quantityInfo = new QuantityInfo(Length.Info.Name, - new UnitInfo[]{ - new UnitInfo(LengthUnit.Meter, "Meters", baseUnits), - new UnitInfo(LengthUnit.Foot, "Feet", baseUnits) }, + new UnitInfo[] { + new(LengthUnit.Meter, "Meters", baseUnits), + new(LengthUnit.Foot, "Feet", baseUnits) }, LengthUnit.Meter, Length.Zero, Length.BaseDimensions); var result = quantityInfo.GetUnitInfosFor(baseUnits); diff --git a/UnitsNet.Tests/QuantityTest.cs b/UnitsNet.Tests/QuantityTest.cs index 5085e531ac..45bb7f0883 100644 --- a/UnitsNet.Tests/QuantityTest.cs +++ b/UnitsNet.Tests/QuantityTest.cs @@ -44,54 +44,25 @@ public void From_GivenValueAndUnit_ReturnsQuantity() } [Fact] - public void GetInfo_GivenLength_ReturnsQuantityInfoForLength() + public void ByName_GivenLength_ReturnsQuantityInfoForLength() { - var knownLengthUnits = new Enum[] { LengthUnit.Meter, LengthUnit.Centimeter, LengthUnit.Kilometer }; - var knownLengthUnitNames = new[] { "Meter", "Centimeter", "Kilometer" }; - var lengthUnitCount = Enum.GetValues(typeof(LengthUnit)).Length - 1; // Exclude LengthUnit.Undefined - - QuantityInfo quantityInfo = Quantity.GetInfo(QuantityType.Length); + QuantityInfo quantityInfo = Quantity.ByName["Length"]; Assert.Equal("Length", quantityInfo.Name); - Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); - // Obsolete members - Assert.Superset(knownLengthUnitNames.ToHashSet(), quantityInfo.UnitNames.ToHashSet()); - Assert.Superset(knownLengthUnits.ToHashSet(), quantityInfo.Units.ToHashSet()); - Assert.Equal(lengthUnitCount, quantityInfo.UnitNames.Length); - Assert.Equal(lengthUnitCount, quantityInfo.Units.Length); - Assert.Equal(typeof(LengthUnit), quantityInfo.UnitType); - Assert.Equal(typeof(Length), quantityInfo.ValueType); - Assert.Equal(Length.Zero, quantityInfo.Zero); + Assert.Same(Length.Info, quantityInfo); } [Fact] - public void GetInfo_GivenMass_ReturnsQuantityInfoForMass() + public void ByName_GivenMass_ReturnsQuantityInfoForMass() { - var knownMassUnits = new Enum[] { MassUnit.Kilogram, MassUnit.Gram, MassUnit.Tonne }; - var knownMassUnitNames = new[] { "Kilogram", "Gram", "Tonne" }; - var massUnitCount = Enum.GetValues(typeof(MassUnit)).Length - 1; // Exclude MassUnit.Undefined - - QuantityInfo quantityInfo = Quantity.GetInfo(QuantityType.Mass); + QuantityInfo quantityInfo = Quantity.ByName["Mass"]; Assert.Equal("Mass", quantityInfo.Name); - // Obsolete members - Assert.Equal(QuantityType.Mass, quantityInfo.QuantityType); - Assert.Superset(knownMassUnitNames.ToHashSet(), quantityInfo.UnitNames.ToHashSet()); - Assert.Superset(knownMassUnits.ToHashSet(), quantityInfo.Units.ToHashSet()); - Assert.Equal(massUnitCount, quantityInfo.UnitNames.Length); - Assert.Equal(massUnitCount, quantityInfo.Units.Length); - Assert.Equal(typeof(MassUnit), quantityInfo.UnitType); - Assert.Equal(typeof(Mass), quantityInfo.ValueType); - Assert.Equal(Mass.Zero, quantityInfo.Zero); + Assert.Same(Mass.Info, quantityInfo); } [Fact] public void Infos_ReturnsKnownQuantityInfoObjects() { - var knownQuantityInfos = new[] - { - Quantity.GetInfo(QuantityType.Length), - Quantity.GetInfo(QuantityType.Force), - Quantity.GetInfo(QuantityType.Mass) - }; + QuantityInfo[] knownQuantityInfos = { Length.Info, Force.Info, Mass.Info }; var infos = Quantity.Infos; Assert.Superset(knownQuantityInfos.ToHashSet(), infos.ToHashSet()); @@ -126,7 +97,7 @@ public void GetUnitInfo_ThrowsKeyNotFoundExceptionIfNotFound() [Fact] public void TryGetUnitInfo_ReturnsFalseIfNotFound() { - bool found = Quantity.TryGetUnitInfo(ConsoleColor.Red, out UnitInfo unitInfo); + bool found = Quantity.TryGetUnitInfo(ConsoleColor.Red, out _); Assert.False(found); } @@ -204,27 +175,5 @@ public void Types_ReturnsKnownQuantityTypes() Assert.Superset(knownQuantities.ToHashSet(), types.ToHashSet()); } - - [Fact] - public void FromQuantityType_GivenUndefinedQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => Quantity.FromQuantityType(QuantityType.Undefined, 0.0)); - } - - [Fact] - public void FromQuantityType_GivenInvalidQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => Quantity.FromQuantityType((QuantityType)(-1), 0.0)); - } - - [Fact] - public void FromQuantityType_GivenLengthQuantityType_ReturnsLengthQuantity() - { - var fromQuantity = Quantity.FromQuantityType(QuantityType.Length, 0.0); - - Assert.Equal(0.0, fromQuantity.Value); - Assert.Equal(QuantityType.Length, fromQuantity.Type); - Assert.Equal(Length.BaseUnit, fromQuantity.Unit); - } } } diff --git a/UnitsNet.Tests/QuantityTests.ToString.cs b/UnitsNet.Tests/QuantityTests.ToString.cs index 06794a8273..f778a6c5c4 100644 --- a/UnitsNet.Tests/QuantityTests.ToString.cs +++ b/UnitsNet.Tests/QuantityTests.ToString.cs @@ -31,17 +31,17 @@ public void ReturnsTheOriginalValueAndUnit() [Fact] public void FormatsNumberUsingGivenCulture() { - var oldCulture = CultureInfo.CurrentUICulture; + var oldCulture = CultureInfo.CurrentCulture; try { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString((IFormatProvider)null)); Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(CultureInfo.InvariantCulture)); Assert.Equal("0,05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(new CultureInfo("nb-NO"))); } finally { - CultureInfo.CurrentUICulture = oldCulture; + CultureInfo.CurrentCulture = oldCulture; } } } diff --git a/UnitsNet.Tests/QuantityTypeConverterTest.cs b/UnitsNet.Tests/QuantityTypeConverterTest.cs index e8f98d76d0..9ae4685f0d 100644 --- a/UnitsNet.Tests/QuantityTypeConverterTest.cs +++ b/UnitsNet.Tests/QuantityTypeConverterTest.cs @@ -35,7 +35,7 @@ static QuantityTypeConverterTest() /// /// Is used for tests that are culture dependent /// - private static CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); + private static readonly CultureInfo Culture = CultureInfo.GetCultureInfo("en-US"); [Theory] [InlineData(typeof(string), true)] @@ -77,7 +77,7 @@ public void ConvertFrom_GivenQuantityStringAndContextWithNoAttributes_ReturnsQua var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - var convertedValue = (Length)converter.ConvertFrom(context, culture, str); + var convertedValue = (Length)converter.ConvertFrom(context, Culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); @@ -96,7 +96,7 @@ public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAttribute_Re new DefaultUnitAttribute(Units.LengthUnit.Centimeter) }); - var convertedValue = (Length)converter.ConvertFrom(context, culture, str); + var convertedValue = (Length)converter.ConvertFrom(context, Culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); @@ -116,7 +116,7 @@ public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAndConvertTo new ConvertToUnitAttribute(Units.LengthUnit.Meter) }); - var convertedValue = (Length)converter.ConvertFrom(context, culture, str); + var convertedValue = (Length)converter.ConvertFrom(context, Culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); @@ -128,7 +128,7 @@ public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Throws(() => converter.ConvertFrom(context, culture, "")); + Assert.Throws(() => converter.ConvertFrom(context, Culture, "")); } [Fact] @@ -137,7 +137,7 @@ public void ConvertFrom_GivenWrongQuantity_ThrowsArgumentException() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Throws(() => converter.ConvertFrom(context, culture, "1m^2")); + Assert.Throws(() => converter.ConvertFrom(context, Culture, "1m^2")); } [Theory] @@ -147,7 +147,6 @@ public void ConvertFrom_GivenWrongQuantity_ThrowsArgumentException() public void ConvertTo_GivenWrongType_ThrowsNotSupportedException(Type value) { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); Length length = Length.FromMeters(1); Assert.Throws(() => converter.ConvertTo(length, value)); @@ -157,7 +156,6 @@ public void ConvertTo_GivenWrongType_ThrowsNotSupportedException(Type value) public void ConvertTo_GivenStringType_ReturnsQuantityString() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); Length length = Length.FromMeters(1); string convertedQuantity = (string)converter.ConvertTo(length, typeof(string)); @@ -172,7 +170,7 @@ public void ConvertTo_GivenSomeQuantityAndContextWithNoAttributes_ReturnsQuantit ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + string convertedQuantity = (string)converter.ConvertTo(context, Culture, length, typeof(string)); Assert.Equal("1 m", convertedQuantity); } @@ -184,7 +182,7 @@ public void ConvertTo_GivenSomeQuantityAndContextWithoutProperty_ReturnsQuantity ITypeDescriptorContext context = new TypeDescriptorContext(); Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + string convertedQuantity = (string)converter.ConvertTo(context, Culture, length, typeof(string)); Assert.Equal("1 m", convertedQuantity); } @@ -199,39 +197,39 @@ public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUn }); Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + string convertedQuantity = (string)converter.ConvertTo(context, Culture, length, typeof(string)); Assert.Equal("10 dm", convertedQuantity); } [Fact] - public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitFormatAsValueOnly() + public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitFormat() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { - new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter, "v") + new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter, "f2") }); Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + string convertedQuantity = (string)converter.ConvertTo(context, Culture, length, typeof(string)); - Assert.Equal("10", convertedQuantity); + Assert.Equal("10.00 dm", convertedQuantity); } [Fact] - public void ConvertTo_TestDisplayAsFormattingWithoutDefinedUnit_ReturnsQuantityStringWithQuantityUnitAndFormattedAsValueOnly() + public void ConvertTo_TestDisplayAsFormattingWithoutDefinedUnit_ReturnsQuantityStringWithNumericFormat() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { - new DisplayAsUnitAttribute(null, "v") + new DisplayAsUnitAttribute(null, "f2") }); Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + string convertedQuantity = (string)converter.ConvertTo(context, Culture, length, typeof(string)); - Assert.Equal("1", convertedQuantity); + Assert.Equal("1.00 m", convertedQuantity); } [Fact] @@ -245,7 +243,7 @@ public void ConvertTo_GivenSomeQuantityAndContextWithDisplayAsUnitAttributes_Ret Length length = Length.FromMeters(1); string convertedQuantityDefaultCulture = (string)converter.ConvertTo(length, typeof(string)); - string convertedQuantitySpecificCulture = (string)converter.ConvertTo(context, culture, length, typeof(string)); + string convertedQuantitySpecificCulture = (string)converter.ConvertTo(context, Culture, length, typeof(string)); Assert.Equal("1 m", convertedQuantityDefaultCulture); Assert.Equal("10 dm", convertedQuantitySpecificCulture); @@ -278,7 +276,7 @@ public void ConvertFrom_GivenDefaultUnitAttributeWithWrongUnitType_ThrowsArgumen new DefaultUnitAttribute(Units.VolumeUnit.CubicMeter) }); - Assert.Throws(() => converter.ConvertFrom(context, culture, "1")); + Assert.Throws(() => converter.ConvertFrom(context, Culture, "1")); } [Fact] @@ -287,8 +285,8 @@ public void ConvertFrom_GivenStringWithPower_1() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m")); - Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m^1")); + Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, Culture, "1m")); + Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, Culture, "1m^1")); } [Fact] @@ -297,8 +295,8 @@ public void ConvertFrom_GivenStringWithPower_2() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m²")); - Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m^2")); + Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, Culture, "1m²")); + Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, Culture, "1m^2")); } [Fact] @@ -307,8 +305,8 @@ public void ConvertFrom_GivenStringWithPower_3() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m³")); - Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m^3")); + Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, Culture, "1m³")); + Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, Culture, "1m^3")); } [Fact] @@ -317,8 +315,8 @@ public void ConvertFrom_GivenStringWithPower_4() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m⁴")); - Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m^4")); + Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, Culture, "1m⁴")); + Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, Culture, "1m^4")); } [Fact] @@ -327,8 +325,8 @@ public void ConvertFrom_GivenStringWithPower_minus1() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K⁻¹")); - Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K^-1")); + Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, Culture, "1K⁻¹")); + Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, Culture, "1K^-1")); } [Fact] @@ -337,9 +335,9 @@ public void ConvertFrom_GivenStringWithPower_minus2() var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s⁻¹·m⁻²")); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s^-1·m^-2")); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg*s^-1*m^-2")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, Culture, "1kg·s⁻¹·m⁻²")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, Culture, "1kg·s^-1·m^-2")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, Culture, "1kg*s^-1*m^-2")); } } } diff --git a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs index 0c6edeeeab..a499007a34 100644 --- a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs +++ b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs @@ -42,10 +42,11 @@ protected override T DeserializeObject(string xml) #region Serialization tests [Fact] - public void DoubleQuantity_SerializedWithDoubleValueAndIntegerUnit() + public void DoubleQuantity_SerializedWithDoubleValueAndunitInt() { var quantity = new Mass(1.20, MassUnit.Milligram); - var expectedJson = "{\"Value\":1.2,\"Unit\":16}"; + var unitInt = (int)quantity.Unit; + var expectedJson = $"{{\"Value\":1.2,\"Unit\":{unitInt}}}"; var json = SerializeObject(quantity); @@ -53,70 +54,71 @@ public void DoubleQuantity_SerializedWithDoubleValueAndIntegerUnit() } [Fact] - public void DecimalQuantity_SerializedWithDecimalValueValueAndIntegerUnit() + public void DecimalQuantity_SerializedWithDecimalValueValueAndunitInt() { var quantity = new Information(1.20m, InformationUnit.Exabyte); - var expectedJson = "{\"Value\":1.20,\"Unit\":4}"; + var unitInt = (int)InformationUnit.Exabyte; + var expectedJson = $"{{\"Value\":1.20,\"Unit\":{unitInt}}}"; var json = SerializeObject(quantity); Assert.Equal(expectedJson, json); } - - [Fact] - public void InterfaceObject_IncludesTypeInformation() - { - var testObject = new TestInterfaceObject { Quantity = new Information(1.20m, InformationUnit.Exabyte) }; - var expectedJson = "{\"Quantity\":{\"__type\":\"Information:#UnitsNet\",\"Value\":1.20,\"Unit\":4}}"; - - var json = SerializeObject(testObject); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationException() - { - var testObject = new TestInterfaceObject { Quantity = new Volume(1.2, VolumeUnit.Microliter) }; - - Assert.Throws(() => SerializeObject(testObject)); - } #endregion #region Deserialization tests [Fact] - public void DoubleQuantity_DeserializedFromDoubleValueAndIntegerUnit() + public void DoubleQuantity_DeserializedFromDoubleValueAndunitInt() { - var json = "{\"Value\":1.2,\"Unit\":16}"; + var expectedUnit = MassUnit.Milligram; + var unitInt = (int)expectedUnit; + var json = $"{{\"Value\":1.2,\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); Assert.Equal(1.2, quantity.Value); - Assert.Equal(MassUnit.Milligram, quantity.Unit); + Assert.Equal(expectedUnit, quantity.Unit); } [Fact] - public void DoubleQuantity_DeserializedFromQuotedDoubleValueAndIntegerUnit() + public void DoubleQuantity_DeserializedFromQuotedDoubleValueAndunitInt() { - var json = "{\"Value\":\"1.2\",\"Unit\":16}"; + var expectedUnit = MassUnit.Milligram; + var unitInt = (int)expectedUnit; + var json = $"{{\"Value\":\"1.2\",\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); Assert.Equal(1.2, quantity.Value); - Assert.Equal(MassUnit.Milligram, quantity.Unit); + Assert.Equal(expectedUnit, quantity.Unit); } [Fact] - public void DoubleZeroQuantity_DeserializedFromIntegerUnitAndNoValue() + public void DoubleZeroQuantity_DeserializedFromunitIntAndNoValue() { - var json = "{\"Unit\":16}"; + var expectedUnit = MassUnit.Milligram; + var unitInt = (int)expectedUnit; + var json = $"{{\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); Assert.Equal(0, quantity.Value); - Assert.Equal(MassUnit.Milligram, quantity.Unit); + Assert.Equal(expectedUnit, quantity.Unit); + } + + [Fact] + public void InterfaceObject_IncludesTypeInformation() + { + var unit = InformationUnit.Exabyte; + var unitInt = (int)unit; + var testObject = new TestInterfaceObject { Quantity = new Information(1.20m, unit) }; + var expectedJson = $"{{\"Quantity\":{{\"__type\":\"Information:#UnitsNet\",\"Value\":1.20,\"Unit\":{unitInt}}}}}"; + + var json = SerializeObject(testObject); + + Assert.Equal(expectedJson, json); } [Fact] @@ -140,40 +142,54 @@ public void DoubleZeroBaseQuantity_DeserializedFromEmptyInput() Assert.Equal(0, quantity.Value); Assert.Equal(Mass.BaseUnit, quantity.Unit); } - + [Fact] - public void DecimalQuantity_DeserializedFromDecimalValueAndIntegerUnit() + public void DecimalQuantity_DeserializedFromDecimalValueAndUnitInt() { - var json = "{\"Value\":1.200,\"Unit\":4}"; + var expectedUnit = InformationUnit.Exabyte; + var unitInt = (int)expectedUnit; + var json = $"{{\"Value\":1.200,\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); Assert.Equal(1.200m, quantity.Value); Assert.Equal("1.200", quantity.Value.ToString(CultureInfo.InvariantCulture)); - Assert.Equal(InformationUnit.Exabyte, quantity.Unit); + Assert.Equal(expectedUnit, quantity.Unit); } [Fact] - public void DecimalQuantity_DeserializedFromQuotedDecimalValueAndIntegerUnit() + public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationException() { - var json = "{\"Value\":\"1.200\",\"Unit\":4}"; + var testObject = new TestInterfaceObject { Quantity = new Volume(1.2, VolumeUnit.Microliter) }; + + Assert.Throws(() => SerializeObject(testObject)); + } + + [Fact] + public void DecimalQuantity_DeserializedFromQuotedDecimalValueAndUnitInt() + { + var expectedUnit = InformationUnit.Exabyte; + var unitInt = (int)expectedUnit; + var json = $"{{\"Value\":\"1.200\",\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); Assert.Equal(1.200m, quantity.Value); Assert.Equal("1.200", quantity.Value.ToString(CultureInfo.InvariantCulture)); - Assert.Equal(InformationUnit.Exabyte, quantity.Unit); + Assert.Equal(expectedUnit, quantity.Unit); } [Fact] - public void DecimalZeroQuantity_DeserializedFromIntegerUnitAndNoValue() + public void DecimalZeroQuantity_DeserializedFromUnitIntAndNoValue() { - var json = "{\"Unit\":4}"; + var expectedUnit = InformationUnit.Exabyte; + var unitInt = (int)expectedUnit; + var json = $"{{\"Unit\":{unitInt}}}"; var quantity = DeserializeObject(json); Assert.Equal(0, quantity.Value); - Assert.Equal(InformationUnit.Exabyte, quantity.Unit); + Assert.Equal(expectedUnit, quantity.Unit); } [Fact] @@ -182,7 +198,7 @@ public void DecimalBaseUnitQuantity_DeserializedFromDecimalValueAndNoUnit() var json = "{\"Value\":1.200}"; var quantity = DeserializeObject(json); - + Assert.Equal(1.200m, quantity.Value); Assert.Equal("1.200", quantity.Value.ToString(CultureInfo.InvariantCulture)); Assert.Equal(Information.BaseUnit, quantity.Unit); diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs index c12c78ea76..238e857dd3 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs @@ -222,15 +222,14 @@ public void GetDefaultAbbreviationThrowsNotImplementedExceptionIfNoneExist() public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() { var oldCurrentCulture = CultureInfo.CurrentCulture; - var oldCurrentUICulture = CultureInfo.CurrentUICulture; try { // CurrentCulture affects number formatting, such as comma or dot as decimal separator. - // CurrentUICulture affects localization, in this case the abbreviation. + // CurrentCulture affects localization, in this case the abbreviation. // Zulu (South Africa) var zuluCulture = new CultureInfo("zu-ZA"); - CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = zuluCulture; + CultureInfo.CurrentCulture = zuluCulture; var abbreviationsCache = new UnitAbbreviationsCache(); abbreviationsCache.MapUnitToAbbreviation(CustomUnit.Unit1, AmericanCulture, "US english abbreviation for Unit1"); @@ -244,7 +243,6 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() finally { CultureInfo.CurrentCulture = oldCurrentCulture; - CultureInfo.CurrentUICulture = oldCurrentUICulture; } } diff --git a/UnitsNet.Tests/UnitConverterTest.cs b/UnitsNet.Tests/UnitConverterTest.cs index 421d7fef23..fab0694f48 100644 --- a/UnitsNet.Tests/UnitConverterTest.cs +++ b/UnitsNet.Tests/UnitConverterTest.cs @@ -112,8 +112,8 @@ public void ConversionForUnitsOfCustomQuantity(double fromValue, HowMuchUnit fro { // Intentionally don't map conversion Some->Some, it is not necessary var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.ATon, x => new HowMuch(x.Value * 2, HowMuchUnit.ATon)); - unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.AShitTon, x => new HowMuch(x.Value * 10, HowMuchUnit.AShitTon)); + unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.ATon, x => new HowMuch((double)x.Value * 2, HowMuchUnit.ATon)); + unitConverter.SetConversionFunction(HowMuchUnit.Some, HowMuchUnit.AShitTon, x => new HowMuch((double)x.Value * 10, HowMuchUnit.AShitTon)); var foundConversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); var converted = foundConversionFunction(new HowMuch(fromValue, fromUnit)); diff --git a/UnitsNet.Tests/UnitSystemTests.cs b/UnitsNet.Tests/UnitSystemTests.cs index b0da0923ca..a3b106ca9b 100644 --- a/UnitsNet.Tests/UnitSystemTests.cs +++ b/UnitsNet.Tests/UnitSystemTests.cs @@ -27,15 +27,15 @@ public void ConstructorThrowsArgumentNullExceptionForNullBaseUnits() } [Theory] - [InlineData(LengthUnit.Undefined, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Undefined, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Undefined, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Undefined, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Undefined, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Undefined, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Undefined)] - public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit length, MassUnit mass, DurationUnit time, ElectricCurrentUnit current, - TemperatureUnit temperature, AmountOfSubstanceUnit amount, LuminousIntensityUnit luminousIntensity) + [InlineData(null, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, null, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, null, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, null, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, null, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, null, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, null)] + public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit? length, MassUnit? mass, DurationUnit? time, ElectricCurrentUnit? current, + TemperatureUnit? temperature, AmountOfSubstanceUnit? amount, LuminousIntensityUnit? luminousIntensity) { var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); Assert.Throws(() => new UnitSystem(baseUnits)); @@ -138,9 +138,6 @@ public void InequalityOperatorIsImplementedCorrectly() [Fact] public void SIUnitSystemHasCorrectBaseUnits() { - var siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - Assert.Equal(LengthUnit.Meter, UnitSystem.SI.BaseUnits.Length); Assert.Equal(MassUnit.Kilogram, UnitSystem.SI.BaseUnits.Mass); Assert.Equal(DurationUnit.Second, UnitSystem.SI.BaseUnits.Time); diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index d057f436ae..bad664ac01 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -1,7 +1,7 @@  - net5.0;net48 + net6.0;net48 UnitsNet.Tests latest true diff --git a/UnitsNet.WindowsRuntimeComponent.sln b/UnitsNet.WindowsRuntimeComponent.sln deleted file mode 100644 index 4b394489cc..0000000000 --- a/UnitsNet.WindowsRuntimeComponent.sln +++ /dev/null @@ -1,42 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27004.2002 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.WindowsRuntimeComponent", "UnitsNet.WindowsRuntimeComponent\UnitsNet.WindowsRuntimeComponent.csproj", "{2DA428CA-BFE1-43FA-86D2-7CB42289D596}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|ARM.ActiveCfg = Debug|ARM - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|ARM.Build.0 = Debug|ARM - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|x64.ActiveCfg = Debug|x64 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|x64.Build.0 = Debug|x64 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|x86.ActiveCfg = Debug|x86 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Debug|x86.Build.0 = Debug|x86 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|Any CPU.Build.0 = Release|Any CPU - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|ARM.ActiveCfg = Release|ARM - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|ARM.Build.0 = Release|ARM - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|x64.ActiveCfg = Release|x64 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|x64.Build.0 = Release|x64 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|x86.ActiveCfg = Release|x86 - {2DA428CA-BFE1-43FA-86D2-7CB42289D596}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {F00A533B-6E8A-4169-9018-F9D6232A7E3C} - EndGlobalSection -EndGlobal diff --git a/UnitsNet.WindowsRuntimeComponent/AmbiguousUnitParseException.cs b/UnitsNet.WindowsRuntimeComponent/AmbiguousUnitParseException.cs deleted file mode 100644 index 7eaea890c4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/AmbiguousUnitParseException.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// 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 , because both - /// and - /// have "pt" as their abbreviation. - /// - internal class AmbiguousUnitParseException : UnitsNetException - { - /// - public AmbiguousUnitParseException(string message) : base(message) - { - HResult = 2; - } - - /// - public AmbiguousUnitParseException(string message, Exception innerException) : base(message, innerException) - { - HResult = 2; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/AssemblyInfo.cs b/UnitsNet.WindowsRuntimeComponent/AssemblyInfo.cs deleted file mode 100644 index ef8f9364ec..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/AssemblyInfo.cs +++ /dev/null @@ -1,5 +0,0 @@ -// Licensed under MIT 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; -[assembly: CLSCompliant(true)] diff --git a/UnitsNet.WindowsRuntimeComponent/BaseDimensions.cs b/UnitsNet.WindowsRuntimeComponent/BaseDimensions.cs deleted file mode 100644 index 4fecf8a80f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/BaseDimensions.cs +++ /dev/null @@ -1,188 +0,0 @@ -// Licensed under MIT 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 -{ - /// - /// Represents the base dimensions of a quantity. - /// - public sealed class BaseDimensions - { - /// - 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; - } - - /// - /// Checks if the dimensions represent a base quantity. - /// - /// True if the dimensions represent a base quantity, otherwise false. - 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; - } - - /// - /// Checks if the dimensions represent a derived quantity. - /// - /// True if the dimensions represent a derived quantity, otherwise false. - public bool IsDerivedQuantity() - { - return !IsBaseQuantity() && !IsDimensionless(); - } - - /// - /// Checks if this base dimensions object represents a dimensionless quantity. - /// - /// True if this object represents a dimensionless quantity, otherwise false. - public bool IsDimensionless() - { - return Equals(this, Dimensionless); - } - - /// - public override bool Equals(object obj) - { - if(!(obj is BaseDimensions)) - return false; - - var other = (BaseDimensions)obj; - - return Length == other.Length && - Mass == other.Mass && - Time == other.Time && - Current == other.Current && - Temperature == other.Temperature && - Amount == other.Amount && - LuminousIntensity == other.LuminousIntensity; - } - - /// - public override int GetHashCode() - { - return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); - } - - /// - /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension. - /// - /// Other dimensions. - /// Resulting dimensions. - 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); - } - - /// - /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension. - /// - /// Other dimensions. - /// Resulting dimensions. - 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); - } - - /// - 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); - } - } - - /// - /// Gets the length dimensions (L). - /// - public int Length { get; } - - /// - /// Gets the mass dimensions (M). - /// - public int Mass{ get; } - - /// - /// Gets the time dimensions (T). - /// - public int Time{ get; } - - /// - /// Gets the electric current dimensions (I). - /// - public int Current{ get; } - - /// - /// Gets the temperature dimensions (Θ). - /// - public int Temperature{ get; } - - /// - /// Gets the amount of substance dimensions (N). - /// - public int Amount{ get; } - - /// - /// Gets the luminous intensity dimensions (J). - /// - public int LuminousIntensity{ get; } - - /// - /// Represents a dimensionless (unitless) quantity. - /// - public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/BaseUnits.cs b/UnitsNet.WindowsRuntimeComponent/BaseUnits.cs deleted file mode 100644 index 240f8e88d5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/BaseUnits.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Licensed under MIT 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.Text; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// Represents the base units for a quantity. All quantities, both base and derived, can be - /// represented by a combination of these seven base units. - /// - public sealed class BaseUnits - { - /// - /// 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. - /// - /// The length unit (L). - /// The mass unit (M). - /// The time unit (T). - /// The electric current unit (I). - /// The temperature unit (Θ). - /// The amount of substance unit (N). - /// The luminous intensity unit (J). - public BaseUnits(LengthUnit length, MassUnit mass, DurationUnit time, ElectricCurrentUnit current, - TemperatureUnit temperature, AmountOfSubstanceUnit amount, LuminousIntensityUnit luminousIntensity) - { - Length = length; - Mass = mass; - Time = time; - Current = current; - Temperature = temperature; - Amount = amount; - LuminousIntensity = luminousIntensity; - } - - /// - public override bool Equals(object obj) - { - if(obj is null || !(obj is BaseUnits)) - return false; - - return Equals((BaseUnits)obj); - } - - /// - /// Checks if all of the base units are equal to another instance's. - /// - /// The other instance to check if equal to. - /// True if equal, otherwise false. - [Windows.Foundation.Metadata.DefaultOverload] - 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; - } - - /// - public override int GetHashCode() - { - return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); - } - - /// - public override string ToString() - { - var sb = new StringBuilder(); - - sb.AppendFormat("[Length]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Length)); - sb.AppendFormat("[Mass]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Mass)); - sb.AppendFormat("[Time]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Time)); - sb.AppendFormat("[Current]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Current)); - sb.AppendFormat("[Temperature]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Temperature)); - sb.AppendFormat("[Amount]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Amount)); - sb.AppendFormat("[LuminousIntensity]: {0}", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LuminousIntensity)); - - return sb.ToString(); - } - - /// - /// Gets the length unit (L). - /// - public LengthUnit Length { get; } - - /// - /// Gets the mass unit (M). - /// - public MassUnit Mass{ get; } - - /// - /// Gets the time unit (T). - /// - public DurationUnit Time{ get; } - - /// - /// Gets the electric current unit (I). - /// - public ElectricCurrentUnit Current{ get; } - - /// - /// Gets the temperature unit (Θ). - /// - public TemperatureUnit Temperature{ get; } - - /// - /// Gets the amount of substance unit (N). - /// - public AmountOfSubstanceUnit Amount{ get; } - - /// - /// Gets the luminous intensity unit (J). - /// - public LuminousIntensityUnit LuminousIntensity{ get; } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/Comparison.cs b/UnitsNet.WindowsRuntimeComponent/Comparison.cs deleted file mode 100644 index 575707e6b5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/Comparison.cs +++ /dev/null @@ -1,125 +0,0 @@ -// Licensed under MIT 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 -{ - /// - /// Helper methods to perform relative and absolute comparison. - /// - public static class Comparison - { - /// - /// - /// Checks if two values are equal with a given relative or absolute tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between - /// and - /// as a percentage of . A relative tolerance of - /// 0.01 means the - /// absolute difference of and must be within +/- - /// 1%. - /// - /// In this example, the two values will be equal if the value of b is within +/- 1% of a. - /// - /// Equals(a, b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between - /// and - /// as a fixed number. - /// - /// In this example, the two values will be equal if abs( - - /// ) <= 0.01 - /// - /// Equals(a, b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// - /// The reference value. If using relative tolerance, it is the value which the relative - /// tolerance will be calculated against. - /// - /// The value to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// Whether the tolerance is absolute or relative. - /// - 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."); - } - } - - /// - /// Checks if two values are equal with a given relative tolerance. - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between - /// and - /// as a percentage of . A relative tolerance of - /// 0.01 means the - /// absolute difference of and must be within +/- - /// 1%. - /// - /// In this example, the two values will be equal if the value of b is within +/- 1% of a. - /// - /// EqualsRelative(a, b, 0.01); - /// - /// - /// - /// - /// The reference value which the tolerance will be calculated against. - /// The value to compare to. - /// The relative tolerance. Must be greater than or equal to 0. - /// True if the two values are equal within the given relative tolerance, otherwise false. - 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; - } - - /// - /// Checks if two values are equal with a given absolute tolerance. - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between - /// and - /// as a fixed number. - /// - /// In this example, the two values will be equal if abs( - - /// ) <= 0.01 - /// - /// Equals(a, b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// The first value. - /// The second value. - /// The absolute tolerance. Must be greater than or equal to 0. - /// True if the two values are equal within the given absolute tolerance, otherwise false. - 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; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/ComparisonType.cs b/UnitsNet.WindowsRuntimeComponent/ComparisonType.cs deleted file mode 100644 index 18f76cfdd3..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/ComparisonType.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed under MIT 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 -{ - /// - /// Specifies if the comparison between numbers is absolute or relative. - /// - public enum ComparisonType - { - /// - /// Error margin in relative size to a reference value. - /// - Relative, - - /// - /// Error margin as absolute size. - /// - Absolute - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/GlobalConfiguration.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/GlobalConfiguration.cs deleted file mode 100644 index 2dcae79bf9..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/GlobalConfiguration.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed under MIT 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; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - public sealed class GlobalConfiguration - { - /// - /// Defaults to when creating an instance with no culture provided. - /// Can be overridden, but note that this is static and will affect all subsequent usages. - /// - // Windows Runtime Component does not support exposing the IFormatProvider type in public API - internal static IFormatProvider DefaultCulture { get; set; } = CultureInfo.CurrentUICulture; - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/AmplitudeRatio.extra.cs deleted file mode 100644 index 4eaf72c7da..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AmplitudeRatio - { - /// - /// Initializes a new instance of the struct from the specified electric potential - /// referenced to one volt RMS. This assumes both the specified electric potential and the one volt reference have the - /// same - /// resistance. - /// - /// The electric potential referenced to one volt. - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - private AmplitudeRatio(ElectricPotential voltage) - : this() - { - if (voltage.Volts <= 0) - throw new ArgumentOutOfRangeException( - nameof(voltage), - "The base-10 logarithm of a number ≤ 0 is undefined. Voltage must be greater than 0 V."); - - // E(dBV) = 20*log10(value(V)/reference(V)) - _value = 20 * Math.Log10(voltage.Volts / 1); - _unit = AmplitudeRatioUnit.DecibelVolt; - } - - /// - /// Gets an from this . - /// - /// - /// Provides a nicer syntax for converting an amplitude ratio back to a voltage. - /// - /// var voltage = voltageRatio.ToElectricPotential(); - /// - /// - public ElectricPotential ToElectricPotential() - { - // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts( Math.Pow( 10, DecibelVolts / 20 ) ); - } - - /// - /// Converts this to a . - /// - /// The input impedance of the load. This is usually 50, 75 or 600 ohms. - /// http://www.maximintegrated.com/en/app-notes/index.mvp/id/808 - public PowerRatio ToPowerRatio( ElectricResistance impedance ) - { - // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) - return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( impedance.Ohms / 1 ) ); - } - - #region Static Methods - - /// - /// Gets an in decibels (dB) relative to 1 volt RMS from an - /// . - /// - /// The voltage (electric potential) relative to one volt RMS. - public static AmplitudeRatio FromElectricPotential(ElectricPotential voltage) - { - return new AmplitudeRatio(voltage); - } - - #endregion - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Area.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Area.extra.cs deleted file mode 100644 index 1c04a0fb5b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Area.extra.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed under MIT 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; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Area - { - public static Area FromCircleDiameter(Length diameter) - { - var radius = Length.FromMeters(diameter.Meters / 2d); - return FromCircleRadius(radius); - } - - public static Area FromCircleRadius(Length radius) - { - return FromSquareMeters(Math.PI * radius.Meters * radius.Meters); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Density.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Density.extra.cs deleted file mode 100644 index bd498e57a4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Density.extra.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - public sealed partial class Density - { - /// - /// Gets from this . - /// - /// - public Molarity ToMolarity(Mass molecularWeight) - { - return Molarity.FromMolesPerCubicMeter(KilogramsPerCubicMeter / molecularWeight.Kilograms); - } - - #region Static Methods - - /// - /// Get from . - /// - /// - /// - public static Density FromMolarity(Molarity molarity, Mass molecularWeight) - { - return new Density(molarity.MolesPerCubicMeter * molecularWeight.Kilograms, DensityUnit.KilogramPerCubicMeter); - } - - #endregion - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Duration.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Duration.extra.cs deleted file mode 100644 index 2b250848ec..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Duration.extra.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed under MIT 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; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Duration - { - /// - /// Convert a Duration to a TimeSpan. - /// - /// Throws if the TimeSpan can't represent the Duration exactly - /// The TimeSpan with the same time as the duration - public TimeSpan ToTimeSpan() - { - if( Seconds > TimeSpan.MaxValue.TotalSeconds || - Seconds < TimeSpan.MinValue.TotalSeconds ) - throw new ArgumentOutOfRangeException( nameof( Duration ), "The duration is too large or small to fit in a TimeSpan" ); - return TimeSpan.FromSeconds( Seconds ); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/ElectricPotential.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/ElectricPotential.extra.cs deleted file mode 100644 index 1c6a921ed1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/ElectricPotential.extra.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed under MIT 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 -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotential - { - /// - /// Gets an in decibels (dB) relative to 1 volt RMS from this . - /// - /// - /// Provides a nicer syntax for converting a voltage to an amplitude ratio (relative to 1 volt RMS). - /// - /// var voltageRatio = voltage.ToAmplitudeRatio(); - /// - /// - public AmplitudeRatio ToAmplitudeRatio() - { - return AmplitudeRatio.FromElectricPotential(this); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Force.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Force.extra.cs deleted file mode 100644 index 4d0b67dec1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Force.extra.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Force - { - public static Force FromPressureByArea(Pressure p, Area area) - { - double newtons = p.Pascals * area.SquareMeters; - return new Force(newtons, ForceUnit.Newton); - } - - public static Force FromMassByAcceleration(Mass mass, Acceleration acceleration) - { - return new Force(mass.Kilograms * acceleration.MetersPerSecondSquared, ForceUnit.Newton); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Length.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Length.extra.cs deleted file mode 100644 index 9788cabb81..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Length.extra.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Length - { - private const double InchesInOneFoot = 12; - - /// - /// Converts the length to a customary feet/inches combination. - /// - public FeetInches FeetInches - { - get - { - var inInches = Inches; - var feet = Math.Truncate(inInches / InchesInOneFoot); - var inches = inInches % InchesInOneFoot; - - return new FeetInches(feet, inches); - } - } - - /// - /// Get length from combination of feet and inches. - /// - public static Length FromFeetInches(double feet, double inches) - { - return FromInches(InchesInOneFoot*feet + inches); - } - } - - public sealed class FeetInches - { - public FeetInches(double feet, double inches) - { - Feet = feet; - Inches = inches; - } - - public double Feet { get; } - public double Inches { get; } - - public override string ToString() - { - return ToString(null); - } - - public string ToString([CanBeNull] string cultureInfo) - { - // Note that it isn't customary to use fractions - one wouldn't say "I am 5 feet and 4.5 inches". - // So inches are rounded when converting from base units to feet/inches. - var footUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LengthUnit.Foot); - var inchUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LengthUnit.Inch); - - return string.Format(GlobalConfiguration.DefaultCulture, "{0:n0} {1} {2:n0} {3}", Feet, footUnit, Math.Round(Inches), - inchUnit); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Mass.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Mass.extra.cs deleted file mode 100644 index 65838e3a67..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Mass.extra.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Mass - { - public static Mass FromGravitationalForce(Force f) - { - return new Mass(f.KilogramsForce, MassUnit.Kilogram); - } - - /// - /// StonePounds related code makes it easier to work with Stone/Pound combination, which are customarily used in the UK - /// to express body weight. For example, someone weighs 11 stone 4 pounds (about 72 kilograms). - /// - private const double StonesInOnePound = 14.0; - - /// - /// Converts the mass to a customary stone/pounds combination. - /// - public StonePounds StonePounds - { - get - { - var inPounds = Pounds; - - var stones = Math.Truncate(inPounds / StonesInOnePound); - var pounds = inPounds % StonesInOnePound; - - return new StonePounds(stones, pounds); - } - } - - /// - /// Get Mass from combination of stone and pounds. - /// - public static Mass FromStonePounds(double stone, double pounds) - { - return FromPounds(StonesInOnePound*stone + pounds); - } - } - - public sealed class StonePounds - { - public StonePounds(double stone, double pounds) - { - Stone = stone; - Pounds = pounds; - } - - public double Stone { get; } - public double Pounds { get; } - - public override string ToString() - { - return ToString(null); - } - - public string ToString([CanBeNull] string cultureInfo) - { - // Note that it isn't customary to use fractions - one wouldn't say "I am 11 stone and 4.5 pounds". - // So pounds are rounded here. - - var culture = cultureInfo != null ? new CultureInfo(cultureInfo) : GlobalConfiguration.DefaultCulture; - var stoneUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(MassUnit.Stone, culture); - var poundUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(MassUnit.Pound, culture); - - return string.Format(culture, "{0:n0} {1} {2:n0} {3}", - Stone, stoneUnit, Math.Round(Pounds), poundUnit); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Molarity.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Molarity.extra.cs deleted file mode 100644 index cafadaa211..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Molarity.extra.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed under MIT 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 -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Molarity - { - /// - /// Get a from this . - /// - /// - public Density ToDensity(Mass molecularWeight) - { - return Density.FromKilogramsPerCubicMeter(MolesPerCubicMeter * molecularWeight.Kilograms); - } - - #region Static Methods - - /// - /// Get from . - /// - /// - /// - public static Molarity FromDensity(Density density, Mass molecularWeight) - { - return FromMolesPerCubicMeter(density.KilogramsPerCubicMeter / molecularWeight.Kilograms); - } - - #endregion - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Power.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Power.extra.cs deleted file mode 100644 index 9b7eddea43..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Power.extra.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed under MIT 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 -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Power - { - /// - /// Gets a from this relative to one watt. - /// - /// - /// Provides a nicer syntax for converting a power to a power ratio (relative to 1 watt). - /// - /// var powerRatio = power.ToPowerRatio(); - /// - /// - public PowerRatio ToPowerRatio() - { - return PowerRatio.FromPower(this); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/PowerRatio.extra.cs deleted file mode 100644 index bd00d8f5db..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/PowerRatio.extra.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PowerRatio - { - /// - /// Initializes a new instance of the struct from the specified power referenced to one watt. - /// - /// The power relative to one watt. - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - private PowerRatio(Power power) - : this() - { - if (power.Watts <= 0) - throw new ArgumentOutOfRangeException( - nameof(power), "The base-10 logarithm of a number ≤ 0 is undefined. Power must be greater than 0 W."); - - // P(dBW) = 10*log10(value(W)/reference(W)) - _value = 10 * Math.Log10(power.Watts / 1); - _unit = PowerRatioUnit.DecibelWatt; - } - - /// - /// Gets a from this (which is a power level relative to one watt). - /// - /// - /// Provides a nicer syntax for converting a power ratio back to a power. - /// - /// var power = powerRatio.ToPower(); - /// - /// - public Power ToPower() - { - // P(W) = 1W * 10^(P(dBW)/10) - return Power.FromWatts(Math.Pow(10, DecibelWatts / 10)); - } - - /// - /// Gets a from this . - /// - /// The input impedance of the load. This is usually 50, 75 or 600 ohms. - public AmplitudeRatio ToAmplitudeRatio(ElectricResistance impedance) - { - // E(dBV) = 10*log10(Z(Ω)/1) + P(dBW) - return AmplitudeRatio.FromDecibelVolts(10 * Math.Log10(impedance.Ohms / 1) + DecibelWatts); - } - - #region Static Methods - - /// - /// Gets a from a relative to one watt. - /// - /// The power relative to one watt. - public static PowerRatio FromPower(Power power) - { - return new PowerRatio(power); - } - - #endregion - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Temperature.extra.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Temperature.extra.cs deleted file mode 100644 index a9b912396a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantities/Temperature.extra.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Temperature - { - /// - /// Multiply temperature with a in a given . - /// - /// - /// Due to different temperature units having different zero points, we cannot simply - /// multiply or divide a temperature by a factor. We must first convert to the desired unit, then perform the - /// calculation. - /// - /// Factor to multiply by. - /// Unit to perform multiplication in. - /// The resulting . - public Temperature Multiply(double factor, TemperatureUnit unit) - { - double resultInUnit = As(unit) * factor; - return From(resultInUnit, unit); - } - - - /// - /// Divide temperature by a in a given . - /// - /// - /// Due to different temperature units having different zero points, we cannot simply - /// multiply or divide a temperature by a factor. We must first convert to the desired unit, then perform the - /// calculation. - /// - /// Factor to multiply by. - /// Unit to perform multiplication in. - /// The resulting . - public Temperature Divide(double divisor, TemperatureUnit unit) - { - double resultInUnit = As(unit) / divisor; - return From(resultInUnit, unit); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantity.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantity.cs deleted file mode 100644 index bcd047a4f0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/Quantity.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Linq; - -namespace UnitsNet -{ - internal partial class Quantity - { - static Quantity() - { - var quantityTypes = Enum.GetValues(typeof(QuantityType)).Cast().Except(new[] {QuantityType.Undefined}).ToArray(); - Types = quantityTypes; - Names = quantityTypes.Select(qt => qt.ToString()).ToArray(); - } - - /// - /// All enum values of , such as and . - /// - public static QuantityType[] Types { get; } - - /// - /// All enum value names of , such as "Length" and "Mass". - /// - public static string[] Names { get; } - - /// - /// Dynamically construct a quantity. - /// - /// Numeric value. - /// Unit enum value. - /// An object. - /// Unit value is not a know unit enum type. - internal static IQuantity From(double value, Enum unit) - { - if (TryFrom(value, unit, out IQuantity quantity)) - return quantity; - - throw new ArgumentException( - $"Unit value {unit} of type {unit.GetType()} is not a known unit enum type. Expected types like UnitsNet.Units.LengthUnit. Did you pass in a third-party enum type defined outside UnitsNet library?"); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/QuantityParser.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/QuantityParser.cs deleted file mode 100644 index bd859e98c9..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/QuantityParser.cs +++ /dev/null @@ -1,217 +0,0 @@ -// Licensed under MIT 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; -using JetBrains.Annotations; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - - internal delegate TQuantity QuantityFromDelegate(double value, TUnitType fromUnit) - where TQuantity : IQuantity - where TUnitType : Enum; - - internal class QuantityParser - { - /// - /// Allow integer, floating point or exponential number formats. - /// - private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent; - - private readonly UnitAbbreviationsCache _unitAbbreviationsCache; - private 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([NotNull] string str, - [CanBeNull] IFormatProvider formatProvider, - [NotNull] QuantityFromDelegate fromDelegate) - where TQuantity : IQuantity - where TUnitType : Enum - { - if (str == null) throw new ArgumentNullException(nameof(str)); - str = str.Trim(); - - var numFormat = formatProvider != null - ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) - : NumberFormatInfo.CurrentInfo; - - if (numFormat == null) - throw new InvalidOperationException($"No number format was found for the given format provider: {formatProvider}"); - - var regex = CreateRegexForQuantity(formatProvider); - - if (!ExtractValueAndUnit(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([NotNull] string str, - [CanBeNull] IFormatProvider formatProvider, - [NotNull] QuantityFromDelegate fromDelegate, - out TQuantity result) - where TQuantity : IQuantity - where TUnitType : Enum - { - result = default; - - if(string.IsNullOrWhiteSpace(str)) return false; - str = str.Trim(); - - var numFormat = formatProvider != null - ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) - : NumberFormatInfo.CurrentInfo; - - if(numFormat == null) - return false; - - var regex = CreateRegexForQuantity(formatProvider); - - if (!ExtractValueAndUnit(regex, str, out var valueString, out var unitString)) - return false; - - return TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); - } - - /// - /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are compatible. - /// - [SuppressMessage("ReSharper", "UseStringInterpolation")] - internal bool TryParse([NotNull] string str, - [CanBeNull] IFormatProvider formatProvider, - [NotNull] QuantityFromDelegate fromDelegate, - out IQuantity result) - where TQuantity : IQuantity - where TUnitType : Enum - { - if (TryParse(str, formatProvider, fromDelegate, out TQuantity parsedQuantity)) - { - result = parsedQuantity; - return true; - } - - result = default; - return false; - } - - internal string CreateRegexPatternForUnit( - TUnitType unit, - IFormatProvider formatProvider, - bool matchEntireString = true) - where TUnitType : Enum - { - var unitAbbreviations = _unitAbbreviationsCache.GetUnitAbbreviations(unit, formatProvider); - var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); - return matchEntireString ? $"^{pattern}$" : pattern; - } - - private static string GetRegexPatternForUnitAbbreviations(IEnumerable 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 $@"(?.*?)\s?(?{abbreviationsPiped})"; - } - - /// - /// Parse a string given a particular regular expression. - /// - /// Error parsing string. - private TQuantity ParseWithRegex(string valueString, - string unitString, - QuantityFromDelegate fromDelegate, - IFormatProvider formatProvider) - where TQuantity : IQuantity - where TUnitType : Enum - { - var value = double.Parse(valueString, ParseNumberStyles, formatProvider); - var parsedUnit = _unitParser.Parse(unitString, formatProvider); - return fromDelegate(value, parsedUnit); - } - - /// - /// Parse a string given a particular regular expression. - /// - /// Error parsing string. - private bool TryParseWithRegex(string valueString, - string unitString, - QuantityFromDelegate fromDelegate, - IFormatProvider formatProvider, - out TQuantity result) - where TQuantity : IQuantity - where TUnitType : Enum - { - result = default; - - if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) - return false; - - if (!_unitParser.TryParse(unitString, formatProvider, out var parsedUnit)) - return false; - - result = fromDelegate(value, parsedUnit); - return true; - } - - private static bool ExtractValueAndUnit(Regex regex, string str, out string valueString, out string unitString) - { - var 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(IFormatProvider formatProvider) where TUnitType : Enum - { - var unitAbbreviations = _unitAbbreviationsCache.GetAllUnitAbbreviationsForQuantity(typeof(TUnitType), formatProvider); - var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); - - // Match entire string exactly - return $"^{pattern}$"; - } - - private Regex CreateRegexForQuantity([CanBeNull] IFormatProvider formatProvider) where TUnitType : Enum - { - var pattern = CreateRegexPatternForQuantity(formatProvider); - return new Regex(pattern, RegexOptions.Singleline); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitAbbreviationsCache.cs deleted file mode 100644 index c7a10d894f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitAbbreviationsCache.cs +++ /dev/null @@ -1,220 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -using UnitTypeToLookup = System.Collections.Generic.Dictionary; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - public sealed class UnitAbbreviationsCache - { - private readonly Dictionary _lookupsForCulture; - - /// - /// Fallback culture used by and - /// if no abbreviations are found with a given culture. - /// - /// - /// User wants to call or 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. - /// - private static readonly CultureInfo FallbackCulture = new CultureInfo("en-US"); - - public static UnitAbbreviationsCache Default { get; } - - public UnitAbbreviationsCache() - { - _lookupsForCulture = new Dictionary(); - - LoadGeneratedAbbreviations(); - } - - static UnitAbbreviationsCache() - { - Default = new UnitAbbreviationsCache(); - } - - private void LoadGeneratedAbbreviations() - { - foreach(var quantity in Quantity.GetQuantityTypes()) - { - var mapGeneratedLocalizationsMethod = quantity.GetMethod(nameof(Length.MapGeneratedLocalizations), BindingFlags.NonPublic | BindingFlags.Static); - mapGeneratedLocalizationsMethod?.Invoke(null, new object[]{this}); - } - } - - /// - /// 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 or to extend with third-party unit enums - /// in order to or on them later. - /// - /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. - /// Unit abbreviations to add. - /// The type of unit enum. - internal void MapUnitToAbbreviation(TUnitType unit, IFormatProvider formatProvider, params string[] abbreviations) where TUnitType : Enum - { - PerformAbbreviationMapping(unit, formatProvider, false, true, abbreviations); - } - - internal void PerformAbbreviationMapping(Enum unitValue, IFormatProvider formatProvider, bool setAsDefault, bool allowAbbreviationLookup, [NotNull] params string[] abbreviations) - { - if (abbreviations == null) - throw new ArgumentNullException(nameof(abbreviations)); - - formatProvider = formatProvider ?? GlobalConfiguration.DefaultCulture; - - 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); - } - } - - /// - /// 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" - /// - /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. - /// The type of unit enum. - /// The default unit abbreviation string. - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal string GetDefaultAbbreviation(TUnitType unit, IFormatProvider formatProvider = null) where TUnitType : Enum - { - var unitType = typeof(TUnitType); - - if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) - { - if(formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unit, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); - } - - var abbreviations = lookup.GetAbbreviationsForUnit(unit); - if(abbreviations.Count == 0) - { - if(formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unit, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); - } - - return abbreviations.First(); - } - - /// - /// 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" - /// - /// The unit enum type. - /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. - /// The default unit abbreviation string. - internal string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider = null) - { - if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) - { - if(formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); - } - - var abbreviations = lookup.GetAbbreviationsForUnit(unitValue); - if(abbreviations.Count == 0) - { - if(formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); - } - - return abbreviations.First(); - } - - /// - /// Get all abbreviations for unit. - /// - /// Enum type for units. - /// Enum value for unit. - /// The format provider to use for lookup. Defaults to if null. - /// Unit abbreviations associated with unit. - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider formatProvider = null) where TUnitType : Enum - { - return GetUnitAbbreviations(typeof(TUnitType), Convert.ToInt32(unit), formatProvider); - } - - /// - /// Get all abbreviations for unit. - /// - /// Enum type for unit. - /// Enum value for unit. - /// The format provider to use for lookup. Defaults to if null. - /// Unit abbreviations associated with unit. - private string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider formatProvider = null) - { - formatProvider = formatProvider ?? GlobalConfiguration.DefaultCulture; - - if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) - return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; - - var abbreviations = lookup.GetAbbreviationsForUnit(unitValue); - if(abbreviations.Count == 0) - return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; - - return abbreviations.ToArray(); - } - - /// - /// Get all abbreviations for all units of a quantity. - /// - /// Enum type for unit. - /// The format provider to use for lookup. Defaults to if null. - /// Unit abbreviations associated with unit. - internal string[] GetAllUnitAbbreviationsForQuantity(Type unitEnumType, IFormatProvider formatProvider = null) - { - formatProvider = formatProvider ?? GlobalConfiguration.DefaultCulture; - - if(!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) - return formatProvider != FallbackCulture ? GetAllUnitAbbreviationsForQuantity(unitEnumType, FallbackCulture) : new string[] { }; - - return lookup.GetAllUnitAbbreviationsForQuantity(); - } - - internal bool TryGetUnitValueAbbreviationLookup(Type unitType, IFormatProvider formatProvider, out UnitValueAbbreviationLookup unitToAbbreviations) - { - unitToAbbreviations = null; - - formatProvider = formatProvider ?? GlobalConfiguration.DefaultCulture; - - if(!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) - return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; - - if(!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) - return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; - - return true; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitParser.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitParser.cs deleted file mode 100644 index b35a320459..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitParser.cs +++ /dev/null @@ -1,161 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; -using UnitsNet.Units; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - public sealed class UnitParser - { - private readonly UnitAbbreviationsCache _unitAbbreviationsCache; - - public static UnitParser Default { get; } - - public UnitParser(UnitAbbreviationsCache unitAbbreviationsCache) - { - _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; - } - - static UnitParser() - { - Default = new UnitParser(UnitAbbreviationsCache.Default); - } - - /// - /// Parses a unit abbreviation for a given unit enumeration type. - /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer - /// - /// - /// The format provider to use for lookup. Defaults to if null. - /// - /// - internal TUnitType Parse(string unitAbbreviation, [CanBeNull] IFormatProvider formatProvider = null) where TUnitType : Enum - { - return (TUnitType)Parse(unitAbbreviation, typeof(TUnitType)); - } - - /// - /// Parse a unit abbreviation, such as "kg" or "m", to the unit enum value of the enum type - /// . - /// - /// - /// Unit abbreviation, such as "kg" or "m" for and - /// respectively. - /// - /// Unit enum type, such as and . - /// The format provider to use for lookup. Defaults to if null. - /// Unit enum value, such as . - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - internal Enum Parse([NotNull] string unitAbbreviation, Type unitType, [CanBeNull] 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); - - // 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: - 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}"); - } - } - - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// The unit enum value as out result. - /// Type of unit enum. - /// True if successful. - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal bool TryParse(string unitAbbreviation, out TUnitType unit) where TUnitType : Enum - { - return TryParse(unitAbbreviation, null, out unit); - } - - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// The format provider to use for lookup. Defaults to if null. - /// The unit enum value as out result. - /// Type of unit enum. - /// True if successful. - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal bool TryParse(string unitAbbreviation, [CanBeNull] IFormatProvider formatProvider, out TUnitType unit) where TUnitType : Enum - { - unit = default; - - if(!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) - return false; - - unit = (TUnitType)unitObj; - return true; - } - - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// Type of unit enum. - /// The unit enum value as out result. - /// True if successful. - internal bool TryParse(string unitAbbreviation, Type unitType, out Enum unit) - { - return TryParse(unitAbbreviation, unitType, null, out unit); - } - - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// Type of unit enum. - /// The format provider to use for lookup. Defaults to if null. - /// The unit enum value as out result. - /// True if successful. - internal bool TryParse(string unitAbbreviation, Type unitType, [CanBeNull] IFormatProvider formatProvider, 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); - - // 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.WindowsRuntimeComponent/CustomCode/UnitValueAbbreviationLookup.cs b/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitValueAbbreviationLookup.cs deleted file mode 100644 index d74d050ec8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/CustomCode/UnitValueAbbreviationLookup.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed under MIT 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; - -using UnitToAbbreviationMap = System.Collections.Generic.Dictionary>; -using AbbreviationToUnitMap = System.Collections.Generic.Dictionary>; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - internal class UnitValueAbbreviationLookup - { - private readonly UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); - private readonly AbbreviationToUnitMap abbreviationToUnitMap = new AbbreviationToUnitMap(); - private readonly AbbreviationToUnitMap lowerCaseAbbreviationToUnitMap = new AbbreviationToUnitMap(); - - internal string[] GetAllUnitAbbreviationsForQuantity() - { - return unitToAbbreviationMap.Values.SelectMany((abbreviations) => - { - return abbreviations; - } ).Distinct().ToArray(); - } - - internal List GetAbbreviationsForUnit(UnitType unit) where UnitType : Enum - { - return GetAbbreviationsForUnit(Convert.ToInt32(unit)); - } - - internal List GetAbbreviationsForUnit(int unit) - { - if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) - unitToAbbreviationMap[unit] = abbreviations = new List(); - - return abbreviations.Distinct().ToList(); - } - - internal List GetUnitsForAbbreviation(string abbreviation, bool ignoreCase) - { - var lowerCaseAbbreviation = abbreviation.ToLower(); - var key = ignoreCase ? lowerCaseAbbreviation : abbreviation; - var map = ignoreCase ? lowerCaseAbbreviationToUnitMap : abbreviationToUnitMap; - - if(!map.TryGetValue(key, out List units)) - map[key] = units = new List(); - - return units.Distinct().ToList(); - } - - internal void Add(int unit, string abbreviation, bool setAsDefault = false, bool allowAbbreviationLookup = true) - { - var lowerCaseAbbreviation = abbreviation.ToLower(); - - if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) - abbreviationsForUnit = unitToAbbreviationMap[unit] = new List(); - - if(allowAbbreviationLookup) - { - if(!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) - abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List(); - - if(!lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) - lowerCaseAbbreviationToUnitMap[lowerCaseAbbreviation] = unitsForLowerCaseAbbreviation = new List(); - - unitsForLowerCaseAbbreviation.Remove(unit); - unitsForLowerCaseAbbreviation.Add(unit); - - unitsForAbbreviation.Remove(unit); - unitsForAbbreviation.Add(unit); - } - - abbreviationsForUnit.Remove(abbreviation); - - if (setAsDefault) - abbreviationsForUnit.Insert(0, abbreviation); - else - abbreviationsForUnit.Add(abbreviation); - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.g.cs deleted file mode 100644 index fda5dbfd0c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Acceleration.g.cs +++ /dev/null @@ -1,854 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Acceleration : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AccelerationUnit? _unit; - - static Acceleration() - { - BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); - BaseUnit = AccelerationUnit.MeterPerSecondSquared; - MaxValue = new Acceleration(double.MaxValue, BaseUnit); - MinValue = new Acceleration(double.MinValue, BaseUnit); - QuantityType = QuantityType.Acceleration; - Units = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); - Zero = new Acceleration(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Acceleration, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit MeterPerSecondSquared. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Acceleration() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Acceleration(double value, AccelerationUnit unit) - { - if (unit == AccelerationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. - /// - public static AccelerationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Acceleration - /// - public static Acceleration MaxValue { get; } - - /// - /// Represents the smallest possible value of Acceleration - /// - public static Acceleration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Acceleration quantity. - /// - public static AccelerationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. - /// - public static Acceleration Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Acceleration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Acceleration.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double MillistandardGravity => As(AccelerationUnit.MillistandardGravity); - - /// - /// Gets a value of this quantity converted into - /// - public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardGravity => As(AccelerationUnit.StandardGravity); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AccelerationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromCentimetersPerSecondSquared(double centimeterspersecondsquared) - { - double value = (double) centimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromDecimetersPerSecondSquared(double decimeterspersecondsquared) - { - double value = (double) decimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromFeetPerSecondSquared(double feetpersecondsquared) - { - double value = (double) feetpersecondsquared; - return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromInchesPerSecondSquared(double inchespersecondsquared) - { - double value = (double) inchespersecondsquared; - return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKilometersPerSecondSquared(double kilometerspersecondsquared) - { - double value = (double) kilometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerHour(double knotsperhour) - { - double value = (double) knotsperhour; - return new Acceleration(value, AccelerationUnit.KnotPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerMinute(double knotsperminute) - { - double value = (double) knotsperminute; - return new Acceleration(value, AccelerationUnit.KnotPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromKnotsPerSecond(double knotspersecond) - { - double value = (double) knotspersecond; - return new Acceleration(value, AccelerationUnit.KnotPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMetersPerSecondSquared(double meterspersecondsquared) - { - double value = (double) meterspersecondsquared; - return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMicrometersPerSecondSquared(double micrometerspersecondsquared) - { - double value = (double) micrometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMillimetersPerSecondSquared(double millimeterspersecondsquared) - { - double value = (double) millimeterspersecondsquared; - return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromMillistandardGravity(double millistandardgravity) - { - double value = (double) millistandardgravity; - return new Acceleration(value, AccelerationUnit.MillistandardGravity); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromNanometersPerSecondSquared(double nanometerspersecondsquared) - { - double value = (double) nanometerspersecondsquared; - return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Acceleration FromStandardGravity(double standardgravity) - { - double value = (double) standardgravity; - return new Acceleration(value, AccelerationUnit.StandardGravity); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Acceleration unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Acceleration From(double value, AccelerationUnit fromUnit) - { - return new Acceleration((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Acceleration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Acceleration Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Acceleration result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Acceleration result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AccelerationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AccelerationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AccelerationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Acceleration objAcceleration)) throw new ArgumentException("Expected type Acceleration.", nameof(obj)); - - return CompareTo(objAcceleration); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Acceleration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Acceleration objAcceleration)) - return false; - - return Equals(objAcceleration); - } - - public bool Equals(Acceleration other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Acceleration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Acceleration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Acceleration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AccelerationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AccelerationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Acceleration to another Acceleration with the unit representation . - /// - /// A Acceleration with the specified unit. - public Acceleration ToUnit(AccelerationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Acceleration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return _value * 0.304800; - case AccelerationUnit.InchPerSecondSquared: return _value * 0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; - case AccelerationUnit.KnotPerHour: return _value * 0.5144444444444 / 3600; - case AccelerationUnit.KnotPerMinute: return _value * 0.5144444444444 / 60; - case AccelerationUnit.KnotPerSecond: return _value * 0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return _value; - case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; - case AccelerationUnit.MillistandardGravity: return (_value * 9.80665) * 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; - case AccelerationUnit.StandardGravity: return _value * 9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AccelerationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; - case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; - case AccelerationUnit.FootPerSecondSquared: return baseUnitValue / 0.304800; - case AccelerationUnit.InchPerSecondSquared: return baseUnitValue / 0.0254; - case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; - case AccelerationUnit.KnotPerHour: return baseUnitValue / 0.5144444444444 * 3600; - case AccelerationUnit.KnotPerMinute: return baseUnitValue / 0.5144444444444 * 60; - case AccelerationUnit.KnotPerSecond: return baseUnitValue / 0.5144444444444; - case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; - case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; - case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; - case AccelerationUnit.MillistandardGravity: return (baseUnitValue / 9.80665) / 1e-3d; - case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; - case AccelerationUnit.StandardGravity: return baseUnitValue / 9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.g.cs deleted file mode 100644 index 8be229580a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ /dev/null @@ -1,859 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AmountOfSubstance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AmountOfSubstanceUnit? _unit; - - static AmountOfSubstance() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); - BaseUnit = AmountOfSubstanceUnit.Mole; - MaxValue = new AmountOfSubstance(double.MaxValue, BaseUnit); - MinValue = new AmountOfSubstance(double.MinValue, BaseUnit); - QuantityType = QuantityType.AmountOfSubstance; - Units = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); - Zero = new AmountOfSubstance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.AmountOfSubstance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Mole. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public AmountOfSubstance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private AmountOfSubstance(double value, AmountOfSubstanceUnit unit) - { - if (unit == AmountOfSubstanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. - /// - public static AmountOfSubstanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of AmountOfSubstance - /// - public static AmountOfSubstance MaxValue { get; } - - /// - /// Represents the smallest possible value of AmountOfSubstance - /// - public static AmountOfSubstance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the AmountOfSubstance quantity. - /// - public static AmountOfSubstanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Mole. - /// - public static AmountOfSubstance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => AmountOfSubstance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Centimoles => As(AmountOfSubstanceUnit.Centimole); - - /// - /// Gets a value of this quantity converted into - /// - public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); - - /// - /// Gets a value of this quantity converted into - /// - public double Decimoles => As(AmountOfSubstanceUnit.Decimole); - - /// - /// Gets a value of this quantity converted into - /// - public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); - - /// - /// Gets a value of this quantity converted into - /// - public double Megamoles => As(AmountOfSubstanceUnit.Megamole); - - /// - /// Gets a value of this quantity converted into - /// - public double Micromoles => As(AmountOfSubstanceUnit.Micromole); - - /// - /// Gets a value of this quantity converted into - /// - public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); - - /// - /// Gets a value of this quantity converted into - /// - public double Millimoles => As(AmountOfSubstanceUnit.Millimole); - - /// - /// Gets a value of this quantity converted into - /// - public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); - - /// - /// Gets a value of this quantity converted into - /// - public double Moles => As(AmountOfSubstanceUnit.Mole); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); - - /// - /// Gets a value of this quantity converted into - /// - public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AmountOfSubstanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromCentimoles(double centimoles) - { - double value = (double) centimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromCentipoundMoles(double centipoundmoles) - { - double value = (double) centipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromDecimoles(double decimoles) - { - double value = (double) decimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromDecipoundMoles(double decipoundmoles) - { - double value = (double) decipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromKilomoles(double kilomoles) - { - double value = (double) kilomoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromKilopoundMoles(double kilopoundmoles) - { - double value = (double) kilopoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMegamoles(double megamoles) - { - double value = (double) megamoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Megamole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMicromoles(double micromoles) - { - double value = (double) micromoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMicropoundMoles(double micropoundmoles) - { - double value = (double) micropoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMillimoles(double millimoles) - { - double value = (double) millimoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMillipoundMoles(double millipoundmoles) - { - double value = (double) millipoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromMoles(double moles) - { - double value = (double) moles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromNanomoles(double nanomoles) - { - double value = (double) nanomoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromNanopoundMoles(double nanopoundmoles) - { - double value = (double) nanopoundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmountOfSubstance FromPoundMoles(double poundmoles) - { - double value = (double) poundmoles; - return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AmountOfSubstance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUnit) - { - return new AmountOfSubstance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AmountOfSubstance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AmountOfSubstance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out AmountOfSubstance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmountOfSubstanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AmountOfSubstanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AmountOfSubstance objAmountOfSubstance)) throw new ArgumentException("Expected type AmountOfSubstance.", nameof(obj)); - - return CompareTo(objAmountOfSubstance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(AmountOfSubstance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is AmountOfSubstance objAmountOfSubstance)) - return false; - - return Equals(objAmountOfSubstance); - } - - public bool Equals(AmountOfSubstance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AmountOfSubstance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmountOfSubstance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AmountOfSubstanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmountOfSubstanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . - /// - /// A AmountOfSubstance with the specified unit. - public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AmountOfSubstance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AmountOfSubstanceUnit.Centimole: return (_value) * 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (_value * 453.59237) * 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (_value) * 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (_value * 453.59237) * 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (_value) * 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (_value * 453.59237) * 1e3d; - case AmountOfSubstanceUnit.Megamole: return (_value) * 1e6d; - case AmountOfSubstanceUnit.Micromole: return (_value) * 1e-6d; - case AmountOfSubstanceUnit.MicropoundMole: return (_value * 453.59237) * 1e-6d; - case AmountOfSubstanceUnit.Millimole: return (_value) * 1e-3d; - case AmountOfSubstanceUnit.MillipoundMole: return (_value * 453.59237) * 1e-3d; - case AmountOfSubstanceUnit.Mole: return _value; - case AmountOfSubstanceUnit.Nanomole: return (_value) * 1e-9d; - case AmountOfSubstanceUnit.NanopoundMole: return (_value * 453.59237) * 1e-9d; - case AmountOfSubstanceUnit.PoundMole: return _value * 453.59237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AmountOfSubstanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AmountOfSubstanceUnit.Centimole: return (baseUnitValue) / 1e-2d; - case AmountOfSubstanceUnit.CentipoundMole: return (baseUnitValue / 453.59237) / 1e-2d; - case AmountOfSubstanceUnit.Decimole: return (baseUnitValue) / 1e-1d; - case AmountOfSubstanceUnit.DecipoundMole: return (baseUnitValue / 453.59237) / 1e-1d; - case AmountOfSubstanceUnit.Kilomole: return (baseUnitValue) / 1e3d; - case AmountOfSubstanceUnit.KilopoundMole: return (baseUnitValue / 453.59237) / 1e3d; - case AmountOfSubstanceUnit.Megamole: return (baseUnitValue) / 1e6d; - case AmountOfSubstanceUnit.Micromole: return (baseUnitValue) / 1e-6d; - case AmountOfSubstanceUnit.MicropoundMole: return (baseUnitValue / 453.59237) / 1e-6d; - case AmountOfSubstanceUnit.Millimole: return (baseUnitValue) / 1e-3d; - case AmountOfSubstanceUnit.MillipoundMole: return (baseUnitValue / 453.59237) / 1e-3d; - case AmountOfSubstanceUnit.Mole: return baseUnitValue; - case AmountOfSubstanceUnit.Nanomole: return (baseUnitValue) / 1e-9d; - case AmountOfSubstanceUnit.NanopoundMole: return (baseUnitValue / 453.59237) / 1e-9d; - case AmountOfSubstanceUnit.PoundMole: return baseUnitValue / 453.59237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.g.cs deleted file mode 100644 index 3d227c2993..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AmplitudeRatio : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AmplitudeRatioUnit? _unit; - - static AmplitudeRatio() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = AmplitudeRatioUnit.DecibelVolt; - MaxValue = new AmplitudeRatio(double.MaxValue, BaseUnit); - MinValue = new AmplitudeRatio(double.MinValue, BaseUnit); - QuantityType = QuantityType.AmplitudeRatio; - Units = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); - Zero = new AmplitudeRatio(0, BaseUnit); - Info = new QuantityInfo(QuantityType.AmplitudeRatio, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DecibelVolt. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public AmplitudeRatio() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private AmplitudeRatio(double value, AmplitudeRatioUnit unit) - { - if (unit == AmplitudeRatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. - /// - public static AmplitudeRatioUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of AmplitudeRatio - /// - public static AmplitudeRatio MaxValue { get; } - - /// - /// Represents the smallest possible value of AmplitudeRatio - /// - public static AmplitudeRatio MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the AmplitudeRatio quantity. - /// - public static AmplitudeRatioUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. - /// - public static AmplitudeRatio Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => AmplitudeRatio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); - - /// - /// Gets a value of this quantity converted into - /// - public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); - - /// - /// Gets a value of this quantity converted into - /// - public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); - - /// - /// Gets a value of this quantity converted into - /// - public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AmplitudeRatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelMicrovolts(double decibelmicrovolts) - { - double value = (double) decibelmicrovolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelMillivolts(double decibelmillivolts) - { - double value = (double) decibelmillivolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelsUnloaded(double decibelsunloaded) - { - double value = (double) decibelsunloaded; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AmplitudeRatio FromDecibelVolts(double decibelvolts) - { - double value = (double) decibelvolts; - return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AmplitudeRatio unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) - { - return new AmplitudeRatio((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AmplitudeRatio Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AmplitudeRatio Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out AmplitudeRatio result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AmplitudeRatioUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AmplitudeRatioUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AmplitudeRatio objAmplitudeRatio)) throw new ArgumentException("Expected type AmplitudeRatio.", nameof(obj)); - - return CompareTo(objAmplitudeRatio); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(AmplitudeRatio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is AmplitudeRatio objAmplitudeRatio)) - return false; - - return Equals(objAmplitudeRatio); - } - - public bool Equals(AmplitudeRatio other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AmplitudeRatio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmplitudeRatio. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AmplitudeRatioUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmplitudeRatioUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . - /// - /// A AmplitudeRatio with the specified unit. - public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AmplitudeRatio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return _value - 120; - case AmplitudeRatioUnit.DecibelMillivolt: return _value - 60; - case AmplitudeRatioUnit.DecibelUnloaded: return _value - 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AmplitudeRatioUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: return baseUnitValue + 120; - case AmplitudeRatioUnit.DecibelMillivolt: return baseUnitValue + 60; - case AmplitudeRatioUnit.DecibelUnloaded: return baseUnitValue + 2.218487499; - case AmplitudeRatioUnit.DecibelVolt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.g.cs deleted file mode 100644 index c7542bca28..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Angle.g.cs +++ /dev/null @@ -1,890 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Angle : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AngleUnit? _unit; - - static Angle() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = AngleUnit.Degree; - MaxValue = new Angle(double.MaxValue, BaseUnit); - MinValue = new Angle(double.MinValue, BaseUnit); - QuantityType = QuantityType.Angle; - Units = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); - Zero = new Angle(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Angle, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Degree. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Angle() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Angle(double value, AngleUnit unit) - { - if (unit == AngleUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Angle, which is Degree. All conversions go via this value. - /// - public static AngleUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Angle - /// - public static Angle MaxValue { get; } - - /// - /// Represents the smallest possible value of Angle - /// - public static Angle MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Angle quantity. - /// - public static AngleUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Degree. - /// - public static Angle Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Angle.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Angle.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Arcminutes => As(AngleUnit.Arcminute); - - /// - /// Gets a value of this quantity converted into - /// - public double Arcseconds => As(AngleUnit.Arcsecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Centiradians => As(AngleUnit.Centiradian); - - /// - /// Gets a value of this quantity converted into - /// - public double Deciradians => As(AngleUnit.Deciradian); - - /// - /// Gets a value of this quantity converted into - /// - public double Degrees => As(AngleUnit.Degree); - - /// - /// Gets a value of this quantity converted into - /// - public double Gradians => As(AngleUnit.Gradian); - - /// - /// Gets a value of this quantity converted into - /// - public double Microdegrees => As(AngleUnit.Microdegree); - - /// - /// Gets a value of this quantity converted into - /// - public double Microradians => As(AngleUnit.Microradian); - - /// - /// Gets a value of this quantity converted into - /// - public double Millidegrees => As(AngleUnit.Millidegree); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliradians => As(AngleUnit.Milliradian); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanodegrees => As(AngleUnit.Nanodegree); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanoradians => As(AngleUnit.Nanoradian); - - /// - /// Gets a value of this quantity converted into - /// - public double NatoMils => As(AngleUnit.NatoMil); - - /// - /// Gets a value of this quantity converted into - /// - public double Radians => As(AngleUnit.Radian); - - /// - /// Gets a value of this quantity converted into - /// - public double Revolutions => As(AngleUnit.Revolution); - - /// - /// Gets a value of this quantity converted into - /// - public double Tilt => As(AngleUnit.Tilt); - - #endregion - - #region Static Methods - - 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(θ)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AngleUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AngleUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromArcminutes(double arcminutes) - { - double value = (double) arcminutes; - return new Angle(value, AngleUnit.Arcminute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromArcseconds(double arcseconds) - { - double value = (double) arcseconds; - return new Angle(value, AngleUnit.Arcsecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromCentiradians(double centiradians) - { - double value = (double) centiradians; - return new Angle(value, AngleUnit.Centiradian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromDeciradians(double deciradians) - { - double value = (double) deciradians; - return new Angle(value, AngleUnit.Deciradian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromDegrees(double degrees) - { - double value = (double) degrees; - return new Angle(value, AngleUnit.Degree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromGradians(double gradians) - { - double value = (double) gradians; - return new Angle(value, AngleUnit.Gradian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMicrodegrees(double microdegrees) - { - double value = (double) microdegrees; - return new Angle(value, AngleUnit.Microdegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMicroradians(double microradians) - { - double value = (double) microradians; - return new Angle(value, AngleUnit.Microradian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMillidegrees(double millidegrees) - { - double value = (double) millidegrees; - return new Angle(value, AngleUnit.Millidegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromMilliradians(double milliradians) - { - double value = (double) milliradians; - return new Angle(value, AngleUnit.Milliradian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNanodegrees(double nanodegrees) - { - double value = (double) nanodegrees; - return new Angle(value, AngleUnit.Nanodegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNanoradians(double nanoradians) - { - double value = (double) nanoradians; - return new Angle(value, AngleUnit.Nanoradian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromNatoMils(double natomils) - { - double value = (double) natomils; - return new Angle(value, AngleUnit.NatoMil); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromRadians(double radians) - { - double value = (double) radians; - return new Angle(value, AngleUnit.Radian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromRevolutions(double revolutions) - { - double value = (double) revolutions; - return new Angle(value, AngleUnit.Revolution); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Angle FromTilt(double tilt) - { - double value = (double) tilt; - return new Angle(value, AngleUnit.Tilt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Angle unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Angle From(double value, AngleUnit fromUnit) - { - return new Angle((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Angle Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Angle Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Angle result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Angle result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AngleUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AngleUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AngleUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Angle objAngle)) throw new ArgumentException("Expected type Angle.", nameof(obj)); - - return CompareTo(objAngle); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Angle other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Angle objAngle)) - return false; - - return Equals(objAngle); - } - - public bool Equals(Angle other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Angle within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Angle. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AngleUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AngleUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Angle to another Angle with the unit representation . - /// - /// A Angle with the specified unit. - public Angle ToUnit(AngleUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Angle(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AngleUnit.Arcminute: return _value / 60; - case AngleUnit.Arcsecond: return _value / 3600; - case AngleUnit.Centiradian: return (_value * 180 / Math.PI) * 1e-2d; - case AngleUnit.Deciradian: return (_value * 180 / Math.PI) * 1e-1d; - case AngleUnit.Degree: return _value; - case AngleUnit.Gradian: return _value * 0.9; - case AngleUnit.Microdegree: return (_value) * 1e-6d; - case AngleUnit.Microradian: return (_value * 180 / Math.PI) * 1e-6d; - case AngleUnit.Millidegree: return (_value) * 1e-3d; - case AngleUnit.Milliradian: return (_value * 180 / Math.PI) * 1e-3d; - case AngleUnit.Nanodegree: return (_value) * 1e-9d; - case AngleUnit.Nanoradian: return (_value * 180 / Math.PI) * 1e-9d; - case AngleUnit.NatoMil: return _value * 9 / 160; - case AngleUnit.Radian: return _value * 180 / Math.PI; - case AngleUnit.Revolution: return _value * 360; - case AngleUnit.Tilt: return Math.Asin(_value) * 180 / Math.PI; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AngleUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AngleUnit.Arcminute: return baseUnitValue * 60; - case AngleUnit.Arcsecond: return baseUnitValue * 3600; - case AngleUnit.Centiradian: return (baseUnitValue / 180 * Math.PI) / 1e-2d; - case AngleUnit.Deciradian: return (baseUnitValue / 180 * Math.PI) / 1e-1d; - case AngleUnit.Degree: return baseUnitValue; - case AngleUnit.Gradian: return baseUnitValue / 0.9; - case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; - case AngleUnit.Microradian: return (baseUnitValue / 180 * Math.PI) / 1e-6d; - case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; - case AngleUnit.Milliradian: return (baseUnitValue / 180 * Math.PI) / 1e-3d; - case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; - case AngleUnit.Nanoradian: return (baseUnitValue / 180 * Math.PI) / 1e-9d; - case AngleUnit.NatoMil: return baseUnitValue * 160 / 9; - case AngleUnit.Radian: return baseUnitValue / 180 * Math.PI; - case AngleUnit.Revolution: return baseUnitValue / 360; - case AngleUnit.Tilt: return Math.Sin(baseUnitValue / 180 * Math.PI); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.g.cs deleted file mode 100644 index 3ec2e63948..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ApparentEnergy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ApparentEnergyUnit? _unit; - - static ApparentEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = ApparentEnergyUnit.VoltampereHour; - MaxValue = new ApparentEnergy(double.MaxValue, BaseUnit); - MinValue = new ApparentEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.ApparentEnergy; - Units = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); - Zero = new ApparentEnergy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ApparentEnergy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltampereHour. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ApparentEnergy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ApparentEnergy(double value, ApparentEnergyUnit unit) - { - if (unit == ApparentEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. - /// - public static ApparentEnergyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ApparentEnergy - /// - public static ApparentEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of ApparentEnergy - /// - public static ApparentEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ApparentEnergy quantity. - /// - public static ApparentEnergyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. - /// - public static ApparentEnergy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ApparentEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ApparentEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromKilovoltampereHours(double kilovoltamperehours) - { - double value = (double) kilovoltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromMegavoltampereHours(double megavoltamperehours) - { - double value = (double) megavoltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentEnergy FromVoltampereHours(double voltamperehours) - { - double value = (double) voltamperehours; - return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ApparentEnergy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) - { - return new ApparentEnergy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ApparentEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ApparentEnergy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ApparentEnergy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ApparentEnergyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ApparentEnergy objApparentEnergy)) throw new ArgumentException("Expected type ApparentEnergy.", nameof(obj)); - - return CompareTo(objApparentEnergy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ApparentEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ApparentEnergy objApparentEnergy)) - return false; - - return Equals(objApparentEnergy); - } - - public bool Equals(ApparentEnergy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ApparentEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ApparentEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ApparentEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ApparentEnergyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentEnergyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation . - /// - /// A ApparentEnergy with the specified unit. - public ApparentEnergy ToUnit(ApparentEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ApparentEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (_value) * 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (_value) * 1e6d; - case ApparentEnergyUnit.VoltampereHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ApparentEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ApparentEnergyUnit.KilovoltampereHour: return (baseUnitValue) / 1e3d; - case ApparentEnergyUnit.MegavoltampereHour: return (baseUnitValue) / 1e6d; - case ApparentEnergyUnit.VoltampereHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.g.cs deleted file mode 100644 index 9987609fbb..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ApparentPower.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ApparentPower : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ApparentPowerUnit? _unit; - - static ApparentPower() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = ApparentPowerUnit.Voltampere; - MaxValue = new ApparentPower(double.MaxValue, BaseUnit); - MinValue = new ApparentPower(double.MinValue, BaseUnit); - QuantityType = QuantityType.ApparentPower; - Units = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); - Zero = new ApparentPower(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ApparentPower, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Voltampere. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ApparentPower() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ApparentPower(double value, ApparentPowerUnit unit) - { - if (unit == ApparentPowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. - /// - public static ApparentPowerUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ApparentPower - /// - public static ApparentPower MaxValue { get; } - - /// - /// Represents the smallest possible value of ApparentPower - /// - public static ApparentPower MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ApparentPower quantity. - /// - public static ApparentPowerUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. - /// - public static ApparentPower Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ApparentPower.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ApparentPower.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Voltamperes => As(ApparentPowerUnit.Voltampere); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ApparentPowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromGigavoltamperes(double gigavoltamperes) - { - double value = (double) gigavoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromKilovoltamperes(double kilovoltamperes) - { - double value = (double) kilovoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromMegavoltamperes(double megavoltamperes) - { - double value = (double) megavoltamperes; - return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ApparentPower FromVoltamperes(double voltamperes) - { - double value = (double) voltamperes; - return new ApparentPower(value, ApparentPowerUnit.Voltampere); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ApparentPower unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ApparentPower From(double value, ApparentPowerUnit fromUnit) - { - return new ApparentPower((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ApparentPower Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ApparentPower Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ApparentPower result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ApparentPower result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ApparentPowerUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ApparentPowerUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ApparentPowerUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ApparentPowerUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ApparentPower objApparentPower)) throw new ArgumentException("Expected type ApparentPower.", nameof(obj)); - - return CompareTo(objApparentPower); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ApparentPower other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ApparentPower objApparentPower)) - return false; - - return Equals(objApparentPower); - } - - public bool Equals(ApparentPower other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ApparentPower within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ApparentPower other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ApparentPower. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ApparentPowerUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ApparentPowerUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ApparentPower to another ApparentPower with the unit representation . - /// - /// A ApparentPower with the specified unit. - public ApparentPower ToUnit(ApparentPowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ApparentPower(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ApparentPowerUnit.Gigavoltampere: return (_value) * 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (_value) * 1e3d; - case ApparentPowerUnit.Megavoltampere: return (_value) * 1e6d; - case ApparentPowerUnit.Voltampere: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ApparentPowerUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ApparentPowerUnit.Gigavoltampere: return (baseUnitValue) / 1e9d; - case ApparentPowerUnit.Kilovoltampere: return (baseUnitValue) / 1e3d; - case ApparentPowerUnit.Megavoltampere: return (baseUnitValue) / 1e6d; - case ApparentPowerUnit.Voltampere: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.g.cs deleted file mode 100644 index 60b8fce04f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Area.g.cs +++ /dev/null @@ -1,867 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Area : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaUnit? _unit; - - static Area() - { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - BaseUnit = AreaUnit.SquareMeter; - MaxValue = new Area(double.MaxValue, BaseUnit); - MinValue = new Area(double.MinValue, BaseUnit); - QuantityType = QuantityType.Area; - Units = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); - Zero = new Area(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Area, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit SquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Area() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Area(double value, AreaUnit unit) - { - if (unit == AreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Area, which is SquareMeter. All conversions go via this value. - /// - public static AreaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Area - /// - public static Area MaxValue { get; } - - /// - /// Represents the smallest possible value of Area - /// - public static Area MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Area quantity. - /// - public static AreaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. - /// - public static Area Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Area.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Area.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Acres => As(AreaUnit.Acre); - - /// - /// Gets a value of this quantity converted into - /// - public double Hectares => As(AreaUnit.Hectare); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareCentimeters => As(AreaUnit.SquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareDecimeters => As(AreaUnit.SquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareFeet => As(AreaUnit.SquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareInches => As(AreaUnit.SquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareKilometers => As(AreaUnit.SquareKilometer); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMeters => As(AreaUnit.SquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMicrometers => As(AreaUnit.SquareMicrometer); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMiles => As(AreaUnit.SquareMile); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMillimeters => As(AreaUnit.SquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareNauticalMiles => As(AreaUnit.SquareNauticalMile); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareYards => As(AreaUnit.SquareYard); - - /// - /// Gets a value of this quantity converted into - /// - public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); - - #endregion - - #region Static Methods - - 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)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AreaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AreaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromAcres(double acres) - { - double value = (double) acres; - return new Area(value, AreaUnit.Acre); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromHectares(double hectares) - { - double value = (double) hectares; - return new Area(value, AreaUnit.Hectare); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareCentimeters(double squarecentimeters) - { - double value = (double) squarecentimeters; - return new Area(value, AreaUnit.SquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareDecimeters(double squaredecimeters) - { - double value = (double) squaredecimeters; - return new Area(value, AreaUnit.SquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareFeet(double squarefeet) - { - double value = (double) squarefeet; - return new Area(value, AreaUnit.SquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareInches(double squareinches) - { - double value = (double) squareinches; - return new Area(value, AreaUnit.SquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareKilometers(double squarekilometers) - { - double value = (double) squarekilometers; - return new Area(value, AreaUnit.SquareKilometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMeters(double squaremeters) - { - double value = (double) squaremeters; - return new Area(value, AreaUnit.SquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMicrometers(double squaremicrometers) - { - double value = (double) squaremicrometers; - return new Area(value, AreaUnit.SquareMicrometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMiles(double squaremiles) - { - double value = (double) squaremiles; - return new Area(value, AreaUnit.SquareMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareMillimeters(double squaremillimeters) - { - double value = (double) squaremillimeters; - return new Area(value, AreaUnit.SquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareNauticalMiles(double squarenauticalmiles) - { - double value = (double) squarenauticalmiles; - return new Area(value, AreaUnit.SquareNauticalMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromSquareYards(double squareyards) - { - double value = (double) squareyards; - return new Area(value, AreaUnit.SquareYard); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Area FromUsSurveySquareFeet(double ussurveysquarefeet) - { - double value = (double) ussurveysquarefeet; - return new Area(value, AreaUnit.UsSurveySquareFoot); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Area unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Area From(double value, AreaUnit fromUnit) - { - return new Area((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Area Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Area Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Area result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Area result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AreaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AreaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Area objArea)) throw new ArgumentException("Expected type Area.", nameof(obj)); - - return CompareTo(objArea); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Area other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Area objArea)) - return false; - - return Equals(objArea); - } - - public bool Equals(Area other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Area within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Area other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Area. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AreaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Area to another Area with the unit representation . - /// - /// A Area with the specified unit. - public Area ToUnit(AreaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Area(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AreaUnit.Acre: return _value * 4046.85642; - case AreaUnit.Hectare: return _value * 1e4; - case AreaUnit.SquareCentimeter: return _value * 1e-4; - case AreaUnit.SquareDecimeter: return _value * 1e-2; - case AreaUnit.SquareFoot: return _value * 9.290304e-2; - case AreaUnit.SquareInch: return _value * 0.00064516; - case AreaUnit.SquareKilometer: return _value * 1e6; - case AreaUnit.SquareMeter: return _value; - case AreaUnit.SquareMicrometer: return _value * 1e-12; - case AreaUnit.SquareMile: return _value * 2.59e6; - case AreaUnit.SquareMillimeter: return _value * 1e-6; - case AreaUnit.SquareNauticalMile: return _value * 3429904; - case AreaUnit.SquareYard: return _value * 0.836127; - case AreaUnit.UsSurveySquareFoot: return _value * 0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaUnit.Acre: return baseUnitValue / 4046.85642; - case AreaUnit.Hectare: return baseUnitValue / 1e4; - case AreaUnit.SquareCentimeter: return baseUnitValue / 1e-4; - case AreaUnit.SquareDecimeter: return baseUnitValue / 1e-2; - case AreaUnit.SquareFoot: return baseUnitValue / 9.290304e-2; - case AreaUnit.SquareInch: return baseUnitValue / 0.00064516; - case AreaUnit.SquareKilometer: return baseUnitValue / 1e6; - case AreaUnit.SquareMeter: return baseUnitValue; - case AreaUnit.SquareMicrometer: return baseUnitValue / 1e-12; - case AreaUnit.SquareMile: return baseUnitValue / 2.59e6; - case AreaUnit.SquareMillimeter: return baseUnitValue / 1e-6; - case AreaUnit.SquareNauticalMile: return baseUnitValue / 3429904; - case AreaUnit.SquareYard: return baseUnitValue / 0.836127; - case AreaUnit.UsSurveySquareFoot: return baseUnitValue / 0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.g.cs deleted file mode 100644 index 2fef2e1978..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaDensity.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The area density of a two-dimensional object is calculated as the mass per unit area. For paper this is also called grammage. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AreaDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaDensityUnit? _unit; - - static AreaDensity() - { - BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); - BaseUnit = AreaDensityUnit.KilogramPerSquareMeter; - MaxValue = new AreaDensity(double.MaxValue, BaseUnit); - MinValue = new AreaDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.AreaDensity; - Units = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); - Zero = new AreaDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.AreaDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public AreaDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private AreaDensity(double value, AreaDensityUnit unit) - { - if (unit == AreaDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. - /// - public static AreaDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of AreaDensity - /// - public static AreaDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of AreaDensity - /// - public static AreaDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the AreaDensity quantity. - /// - public static AreaDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. - /// - public static AreaDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => AreaDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AreaDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerSquareMeter => As(AreaDensityUnit.GramPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerSquareMeter => As(AreaDensityUnit.MilligramPerSquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AreaDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaDensity FromGramsPerSquareMeter(double gramspersquaremeter) - { - double value = (double) gramspersquaremeter; - return new AreaDensity(value, AreaDensityUnit.GramPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaDensity FromKilogramsPerSquareMeter(double kilogramspersquaremeter) - { - double value = (double) kilogramspersquaremeter; - return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaDensity FromMilligramsPerSquareMeter(double milligramspersquaremeter) - { - double value = (double) milligramspersquaremeter; - return new AreaDensity(value, AreaDensityUnit.MilligramPerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AreaDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AreaDensity From(double value, AreaDensityUnit fromUnit) - { - return new AreaDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AreaDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AreaDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AreaDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out AreaDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AreaDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AreaDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AreaDensity objAreaDensity)) throw new ArgumentException("Expected type AreaDensity.", nameof(obj)); - - return CompareTo(objAreaDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(AreaDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is AreaDensity objAreaDensity)) - return false; - - return Equals(objAreaDensity); - } - - public bool Equals(AreaDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AreaDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AreaDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AreaDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AreaDensity to another AreaDensity with the unit representation . - /// - /// A AreaDensity with the specified unit. - public AreaDensity ToUnit(AreaDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AreaDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AreaDensityUnit.GramPerSquareMeter: return _value / 1000; - case AreaDensityUnit.KilogramPerSquareMeter: return _value; - case AreaDensityUnit.MilligramPerSquareMeter: return _value / 1000000; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaDensityUnit.GramPerSquareMeter: return baseUnitValue * 1000; - case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; - case AreaDensityUnit.MilligramPerSquareMeter: return baseUnitValue * 1000000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs deleted file mode 100644 index 23b081cd9e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ /dev/null @@ -1,688 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A geometric property of an area that reflects how its points are distributed with regard to an axis. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class AreaMomentOfInertia : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly AreaMomentOfInertiaUnit? _unit; - - static AreaMomentOfInertia() - { - BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); - BaseUnit = AreaMomentOfInertiaUnit.MeterToTheFourth; - MaxValue = new AreaMomentOfInertia(double.MaxValue, BaseUnit); - MinValue = new AreaMomentOfInertia(double.MinValue, BaseUnit); - QuantityType = QuantityType.AreaMomentOfInertia; - Units = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); - Zero = new AreaMomentOfInertia(0, BaseUnit); - Info = new QuantityInfo(QuantityType.AreaMomentOfInertia, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit MeterToTheFourth. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public AreaMomentOfInertia() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private AreaMomentOfInertia(double value, AreaMomentOfInertiaUnit unit) - { - if (unit == AreaMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. - /// - public static AreaMomentOfInertiaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of AreaMomentOfInertia - /// - public static AreaMomentOfInertia MaxValue { get; } - - /// - /// Represents the smallest possible value of AreaMomentOfInertia - /// - public static AreaMomentOfInertia MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the AreaMomentOfInertia quantity. - /// - public static AreaMomentOfInertiaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. - /// - public static AreaMomentOfInertia Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => AreaMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromCentimetersToTheFourth(double centimeterstothefourth) - { - double value = (double) centimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromDecimetersToTheFourth(double decimeterstothefourth) - { - double value = (double) decimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromFeetToTheFourth(double feettothefourth) - { - double value = (double) feettothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromInchesToTheFourth(double inchestothefourth) - { - double value = (double) inchestothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromMetersToTheFourth(double meterstothefourth) - { - double value = (double) meterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static AreaMomentOfInertia FromMillimetersToTheFourth(double millimeterstothefourth) - { - double value = (double) millimeterstothefourth; - return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// AreaMomentOfInertia unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fromUnit) - { - return new AreaMomentOfInertia((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static AreaMomentOfInertia Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AreaMomentOfInertia Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out AreaMomentOfInertia result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static AreaMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out AreaMomentOfInertiaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AreaMomentOfInertia objAreaMomentOfInertia)) throw new ArgumentException("Expected type AreaMomentOfInertia.", nameof(obj)); - - return CompareTo(objAreaMomentOfInertia); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(AreaMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is AreaMomentOfInertia objAreaMomentOfInertia)) - return false; - - return Equals(objAreaMomentOfInertia); - } - - public bool Equals(AreaMomentOfInertia other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another AreaMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaMomentOfInertia. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((AreaMomentOfInertiaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaMomentOfInertiaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . - /// - /// A AreaMomentOfInertia with the specified unit. - public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new AreaMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return _value / 1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return _value / 1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return _value * Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return _value * Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return _value; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return _value / 1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(AreaMomentOfInertiaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return baseUnitValue * 1e8; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return baseUnitValue * 1e4; - case AreaMomentOfInertiaUnit.FootToTheFourth: return baseUnitValue / Math.Pow(0.3048, 4); - case AreaMomentOfInertiaUnit.InchToTheFourth: return baseUnitValue / Math.Pow(2.54e-2, 4); - case AreaMomentOfInertiaUnit.MeterToTheFourth: return baseUnitValue; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return baseUnitValue * 1e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.g.cs deleted file mode 100644 index 20c5678fdd..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BitRate.g.cs +++ /dev/null @@ -1,1071 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time. - /// - /// - /// https://en.wikipedia.org/wiki/Bit_rate - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class BitRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly BitRateUnit? _unit; - - static BitRate() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = BitRateUnit.BitPerSecond; - MaxValue = new BitRate(decimal.MaxValue, BaseUnit); - MinValue = new BitRate(decimal.MinValue, BaseUnit); - QuantityType = QuantityType.BitRate; - Units = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); - Zero = new BitRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.BitRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit BitPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public BitRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private BitRate(decimal value, BitRateUnit unit) - { - if (unit == BitRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = value; - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. - /// - public static BitRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of BitRate - /// - public static BitRate MaxValue { get; } - - /// - /// Represents the smallest possible value of BitRate - /// - public static BitRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the BitRate quantity. - /// - public static BitRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. - /// - public static BitRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => BitRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => BitRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BitsPerSecond => As(BitRateUnit.BitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double BytesPerSecond => As(BitRateUnit.BytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(BitRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromBitsPerSecond(double bitspersecond) - { - decimal value = (decimal) bitspersecond; - return new BitRate(value, BitRateUnit.BitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromBytesPerSecond(double bytespersecond) - { - decimal value = (decimal) bytespersecond; - return new BitRate(value, BitRateUnit.BytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExabitsPerSecond(double exabitspersecond) - { - decimal value = (decimal) exabitspersecond; - return new BitRate(value, BitRateUnit.ExabitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExabytesPerSecond(double exabytespersecond) - { - decimal value = (decimal) exabytespersecond; - return new BitRate(value, BitRateUnit.ExabytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExbibitsPerSecond(double exbibitspersecond) - { - decimal value = (decimal) exbibitspersecond; - return new BitRate(value, BitRateUnit.ExbibitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromExbibytesPerSecond(double exbibytespersecond) - { - decimal value = (decimal) exbibytespersecond; - return new BitRate(value, BitRateUnit.ExbibytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGibibitsPerSecond(double gibibitspersecond) - { - decimal value = (decimal) gibibitspersecond; - return new BitRate(value, BitRateUnit.GibibitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGibibytesPerSecond(double gibibytespersecond) - { - decimal value = (decimal) gibibytespersecond; - return new BitRate(value, BitRateUnit.GibibytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGigabitsPerSecond(double gigabitspersecond) - { - decimal value = (decimal) gigabitspersecond; - return new BitRate(value, BitRateUnit.GigabitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromGigabytesPerSecond(double gigabytespersecond) - { - decimal value = (decimal) gigabytespersecond; - return new BitRate(value, BitRateUnit.GigabytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKibibitsPerSecond(double kibibitspersecond) - { - decimal value = (decimal) kibibitspersecond; - return new BitRate(value, BitRateUnit.KibibitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKibibytesPerSecond(double kibibytespersecond) - { - decimal value = (decimal) kibibytespersecond; - return new BitRate(value, BitRateUnit.KibibytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKilobitsPerSecond(double kilobitspersecond) - { - decimal value = (decimal) kilobitspersecond; - return new BitRate(value, BitRateUnit.KilobitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromKilobytesPerSecond(double kilobytespersecond) - { - decimal value = (decimal) kilobytespersecond; - return new BitRate(value, BitRateUnit.KilobytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMebibitsPerSecond(double mebibitspersecond) - { - decimal value = (decimal) mebibitspersecond; - return new BitRate(value, BitRateUnit.MebibitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMebibytesPerSecond(double mebibytespersecond) - { - decimal value = (decimal) mebibytespersecond; - return new BitRate(value, BitRateUnit.MebibytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMegabitsPerSecond(double megabitspersecond) - { - decimal value = (decimal) megabitspersecond; - return new BitRate(value, BitRateUnit.MegabitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromMegabytesPerSecond(double megabytespersecond) - { - decimal value = (decimal) megabytespersecond; - return new BitRate(value, BitRateUnit.MegabytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPebibitsPerSecond(double pebibitspersecond) - { - decimal value = (decimal) pebibitspersecond; - return new BitRate(value, BitRateUnit.PebibitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPebibytesPerSecond(double pebibytespersecond) - { - decimal value = (decimal) pebibytespersecond; - return new BitRate(value, BitRateUnit.PebibytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPetabitsPerSecond(double petabitspersecond) - { - decimal value = (decimal) petabitspersecond; - return new BitRate(value, BitRateUnit.PetabitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromPetabytesPerSecond(double petabytespersecond) - { - decimal value = (decimal) petabytespersecond; - return new BitRate(value, BitRateUnit.PetabytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTebibitsPerSecond(double tebibitspersecond) - { - decimal value = (decimal) tebibitspersecond; - return new BitRate(value, BitRateUnit.TebibitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTebibytesPerSecond(double tebibytespersecond) - { - decimal value = (decimal) tebibytespersecond; - return new BitRate(value, BitRateUnit.TebibytePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTerabitsPerSecond(double terabitspersecond) - { - decimal value = (decimal) terabitspersecond; - return new BitRate(value, BitRateUnit.TerabitPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BitRate FromTerabytesPerSecond(double terabytespersecond) - { - decimal value = (decimal) terabytespersecond; - return new BitRate(value, BitRateUnit.TerabytePerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// BitRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static BitRate From(double value, BitRateUnit fromUnit) - { - return new BitRate((decimal)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static BitRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static BitRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out BitRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out BitRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BitRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out BitRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out BitRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is BitRate objBitRate)) throw new ArgumentException("Expected type BitRate.", nameof(obj)); - - return CompareTo(objBitRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(BitRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is BitRate objBitRate)) - return false; - - return Equals(objBitRate); - } - - public bool Equals(BitRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another BitRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BitRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BitRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((BitRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BitRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this BitRate to another BitRate with the unit representation . - /// - /// A BitRate with the specified unit. - public BitRate ToUnit(BitRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new BitRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal AsBaseUnit() - { - switch(Unit) - { - case BitRateUnit.BitPerSecond: return _value; - case BitRateUnit.BytePerSecond: return _value * 8m; - case BitRateUnit.ExabitPerSecond: return (_value) * 1e18m; - case BitRateUnit.ExabytePerSecond: return (_value * 8m) * 1e18m; - case BitRateUnit.ExbibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (_value) * (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (_value * 8m) * (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (_value) * 1e9m; - case BitRateUnit.GigabytePerSecond: return (_value * 8m) * 1e9m; - case BitRateUnit.KibibitPerSecond: return (_value) * 1024m; - case BitRateUnit.KibibytePerSecond: return (_value * 8m) * 1024m; - case BitRateUnit.KilobitPerSecond: return (_value) * 1e3m; - case BitRateUnit.KilobytePerSecond: return (_value * 8m) * 1e3m; - case BitRateUnit.MebibitPerSecond: return (_value) * (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (_value * 8m) * (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (_value) * 1e6m; - case BitRateUnit.MegabytePerSecond: return (_value * 8m) * 1e6m; - case BitRateUnit.PebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (_value) * 1e15m; - case BitRateUnit.PetabytePerSecond: return (_value * 8m) * 1e15m; - case BitRateUnit.TebibitPerSecond: return (_value) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (_value * 8m) * (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (_value) * 1e12m; - case BitRateUnit.TerabytePerSecond: return (_value * 8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(BitRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case BitRateUnit.BitPerSecond: return baseUnitValue; - case BitRateUnit.BytePerSecond: return baseUnitValue / 8m; - case BitRateUnit.ExabitPerSecond: return (baseUnitValue) / 1e18m; - case BitRateUnit.ExabytePerSecond: return (baseUnitValue / 8m) / 1e18m; - case BitRateUnit.ExbibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.ExbibytePerSecond: return (baseUnitValue / 8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.GibibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024); - case BitRateUnit.GibibytePerSecond: return (baseUnitValue / 8m) / (1024m * 1024 * 1024); - case BitRateUnit.GigabitPerSecond: return (baseUnitValue) / 1e9m; - case BitRateUnit.GigabytePerSecond: return (baseUnitValue / 8m) / 1e9m; - case BitRateUnit.KibibitPerSecond: return (baseUnitValue) / 1024m; - case BitRateUnit.KibibytePerSecond: return (baseUnitValue / 8m) / 1024m; - case BitRateUnit.KilobitPerSecond: return (baseUnitValue) / 1e3m; - case BitRateUnit.KilobytePerSecond: return (baseUnitValue / 8m) / 1e3m; - case BitRateUnit.MebibitPerSecond: return (baseUnitValue) / (1024m * 1024); - case BitRateUnit.MebibytePerSecond: return (baseUnitValue / 8m) / (1024m * 1024); - case BitRateUnit.MegabitPerSecond: return (baseUnitValue) / 1e6m; - case BitRateUnit.MegabytePerSecond: return (baseUnitValue / 8m) / 1e6m; - case BitRateUnit.PebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PebibytePerSecond: return (baseUnitValue / 8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case BitRateUnit.PetabitPerSecond: return (baseUnitValue) / 1e15m; - case BitRateUnit.PetabytePerSecond: return (baseUnitValue / 8m) / 1e15m; - case BitRateUnit.TebibitPerSecond: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TebibytePerSecond: return (baseUnitValue / 8m) / (1024m * 1024 * 1024 * 1024); - case BitRateUnit.TerabitPerSecond: return (baseUnitValue) / 1e12m; - case BitRateUnit.TerabytePerSecond: return (baseUnitValue / 8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs deleted file mode 100644 index 2996405969..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class BrakeSpecificFuelConsumption : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly BrakeSpecificFuelConsumptionUnit? _unit; - - static BrakeSpecificFuelConsumption() - { - BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); - BaseUnit = BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; - MaxValue = new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); - MinValue = new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); - QuantityType = QuantityType.BrakeSpecificFuelConsumption; - Units = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); - Zero = new BrakeSpecificFuelConsumption(0, BaseUnit); - Info = new QuantityInfo(QuantityType.BrakeSpecificFuelConsumption, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerJoule. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public BrakeSpecificFuelConsumption() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private BrakeSpecificFuelConsumption(double value, BrakeSpecificFuelConsumptionUnit unit) - { - if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. - /// - public static BrakeSpecificFuelConsumptionUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of BrakeSpecificFuelConsumption - /// - public static BrakeSpecificFuelConsumption MaxValue { get; } - - /// - /// Represents the smallest possible value of BrakeSpecificFuelConsumption - /// - public static BrakeSpecificFuelConsumption MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the BrakeSpecificFuelConsumption quantity. - /// - public static BrakeSpecificFuelConsumptionUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. - /// - public static BrakeSpecificFuelConsumption Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => BrakeSpecificFuelConsumption.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double gramsperkilowatthour) - { - double value = (double) gramsperkilowatthour; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double kilogramsperjoule) - { - double value = (double) kilogramsperjoule; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double poundspermechanicalhorsepowerhour) - { - double value = (double) poundspermechanicalhorsepowerhour; - return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// BrakeSpecificFuelConsumption unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelConsumptionUnit fromUnit) - { - return new BrakeSpecificFuelConsumption((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static BrakeSpecificFuelConsumption Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsumption result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out BrakeSpecificFuelConsumption result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out BrakeSpecificFuelConsumptionUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is BrakeSpecificFuelConsumption objBrakeSpecificFuelConsumption)) throw new ArgumentException("Expected type BrakeSpecificFuelConsumption.", nameof(obj)); - - return CompareTo(objBrakeSpecificFuelConsumption); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(BrakeSpecificFuelConsumption other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is BrakeSpecificFuelConsumption objBrakeSpecificFuelConsumption)) - return false; - - return Equals(objBrakeSpecificFuelConsumption); - } - - public bool Equals(BrakeSpecificFuelConsumption other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another BrakeSpecificFuelConsumption within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BrakeSpecificFuelConsumption. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((BrakeSpecificFuelConsumptionUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BrakeSpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . - /// - /// A BrakeSpecificFuelConsumption with the specified unit. - public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new BrakeSpecificFuelConsumption(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return _value / 3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return _value; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return _value * 1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(BrakeSpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return baseUnitValue * 3.6e9; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return baseUnitValue; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return baseUnitValue / 1.689659410672e-7; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.g.cs deleted file mode 100644 index 7092060541..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Capacitance.g.cs +++ /dev/null @@ -1,710 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Capacitance is the ability of a body to store an electric charge. - /// - /// - /// https://en.wikipedia.org/wiki/Capacitance - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Capacitance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly CapacitanceUnit? _unit; - - static Capacitance() - { - BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); - BaseUnit = CapacitanceUnit.Farad; - MaxValue = new Capacitance(double.MaxValue, BaseUnit); - MinValue = new Capacitance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Capacitance; - Units = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); - Zero = new Capacitance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Capacitance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Farad. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Capacitance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Capacitance(double value, CapacitanceUnit unit) - { - if (unit == CapacitanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Capacitance, which is Farad. All conversions go via this value. - /// - public static CapacitanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Capacitance - /// - public static Capacitance MaxValue { get; } - - /// - /// Represents the smallest possible value of Capacitance - /// - public static Capacitance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Capacitance quantity. - /// - public static CapacitanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Farad. - /// - public static Capacitance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Capacitance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Capacitance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Farads => As(CapacitanceUnit.Farad); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilofarads => As(CapacitanceUnit.Kilofarad); - - /// - /// Gets a value of this quantity converted into - /// - public double Megafarads => As(CapacitanceUnit.Megafarad); - - /// - /// Gets a value of this quantity converted into - /// - public double Microfarads => As(CapacitanceUnit.Microfarad); - - /// - /// Gets a value of this quantity converted into - /// - public double Millifarads => As(CapacitanceUnit.Millifarad); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanofarads => As(CapacitanceUnit.Nanofarad); - - /// - /// Gets a value of this quantity converted into - /// - public double Picofarads => As(CapacitanceUnit.Picofarad); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(CapacitanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromFarads(double farads) - { - double value = (double) farads; - return new Capacitance(value, CapacitanceUnit.Farad); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromKilofarads(double kilofarads) - { - double value = (double) kilofarads; - return new Capacitance(value, CapacitanceUnit.Kilofarad); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromMegafarads(double megafarads) - { - double value = (double) megafarads; - return new Capacitance(value, CapacitanceUnit.Megafarad); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromMicrofarads(double microfarads) - { - double value = (double) microfarads; - return new Capacitance(value, CapacitanceUnit.Microfarad); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromMillifarads(double millifarads) - { - double value = (double) millifarads; - return new Capacitance(value, CapacitanceUnit.Millifarad); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromNanofarads(double nanofarads) - { - double value = (double) nanofarads; - return new Capacitance(value, CapacitanceUnit.Nanofarad); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Capacitance FromPicofarads(double picofarads) - { - double value = (double) picofarads; - return new Capacitance(value, CapacitanceUnit.Picofarad); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Capacitance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Capacitance From(double value, CapacitanceUnit fromUnit) - { - return new Capacitance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Capacitance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Capacitance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Capacitance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Capacitance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CapacitanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out CapacitanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out CapacitanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Capacitance objCapacitance)) throw new ArgumentException("Expected type Capacitance.", nameof(obj)); - - return CompareTo(objCapacitance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Capacitance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Capacitance objCapacitance)) - return false; - - return Equals(objCapacitance); - } - - public bool Equals(Capacitance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Capacitance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Capacitance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Capacitance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((CapacitanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CapacitanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Capacitance to another Capacitance with the unit representation . - /// - /// A Capacitance with the specified unit. - public Capacitance ToUnit(CapacitanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Capacitance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case CapacitanceUnit.Farad: return _value; - case CapacitanceUnit.Kilofarad: return (_value) * 1e3d; - case CapacitanceUnit.Megafarad: return (_value) * 1e6d; - case CapacitanceUnit.Microfarad: return (_value) * 1e-6d; - case CapacitanceUnit.Millifarad: return (_value) * 1e-3d; - case CapacitanceUnit.Nanofarad: return (_value) * 1e-9d; - case CapacitanceUnit.Picofarad: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(CapacitanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case CapacitanceUnit.Farad: return baseUnitValue; - case CapacitanceUnit.Kilofarad: return (baseUnitValue) / 1e3d; - case CapacitanceUnit.Megafarad: return (baseUnitValue) / 1e6d; - case CapacitanceUnit.Microfarad: return (baseUnitValue) / 1e-6d; - case CapacitanceUnit.Millifarad: return (baseUnitValue) / 1e-3d; - case CapacitanceUnit.Nanofarad: return (baseUnitValue) / 1e-9d; - case CapacitanceUnit.Picofarad: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs deleted file mode 100644 index f8d039bbd6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A unit that represents a fractional change in size in response to a change in temperature. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class CoefficientOfThermalExpansion : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly CoefficientOfThermalExpansionUnit? _unit; - - static CoefficientOfThermalExpansion() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); - BaseUnit = CoefficientOfThermalExpansionUnit.InverseKelvin; - MaxValue = new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); - MinValue = new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); - QuantityType = QuantityType.CoefficientOfThermalExpansion; - Units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); - Zero = new CoefficientOfThermalExpansion(0, BaseUnit); - Info = new QuantityInfo(QuantityType.CoefficientOfThermalExpansion, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit InverseKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public CoefficientOfThermalExpansion() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansionUnit unit) - { - if (unit == CoefficientOfThermalExpansionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value. - /// - public static CoefficientOfThermalExpansionUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of CoefficientOfThermalExpansion - /// - public static CoefficientOfThermalExpansion MaxValue { get; } - - /// - /// Represents the smallest possible value of CoefficientOfThermalExpansion - /// - public static CoefficientOfThermalExpansion MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the CoefficientOfThermalExpansion quantity. - /// - public static CoefficientOfThermalExpansionUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. - /// - public static CoefficientOfThermalExpansion Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => CoefficientOfThermalExpansion.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(double inversedegreecelsius) - { - double value = (double) inversedegreecelsius; - return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(double inversedegreefahrenheit) - { - double value = (double) inversedegreefahrenheit; - return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static CoefficientOfThermalExpansion FromInverseKelvin(double inversekelvin) - { - double value = (double) inversekelvin; - return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// CoefficientOfThermalExpansion unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static CoefficientOfThermalExpansion From(double value, CoefficientOfThermalExpansionUnit fromUnit) - { - return new CoefficientOfThermalExpansion((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static CoefficientOfThermalExpansion Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static CoefficientOfThermalExpansion Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out CoefficientOfThermalExpansion result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out CoefficientOfThermalExpansion result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CoefficientOfThermalExpansionUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static CoefficientOfThermalExpansionUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out CoefficientOfThermalExpansionUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is CoefficientOfThermalExpansion objCoefficientOfThermalExpansion)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj)); - - return CompareTo(objCoefficientOfThermalExpansion); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(CoefficientOfThermalExpansion other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is CoefficientOfThermalExpansion objCoefficientOfThermalExpansion)) - return false; - - return Equals(objCoefficientOfThermalExpansion); - } - - public bool Equals(CoefficientOfThermalExpansion other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another CoefficientOfThermalExpansion within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(CoefficientOfThermalExpansion other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current CoefficientOfThermalExpansion. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((CoefficientOfThermalExpansionUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CoefficientOfThermalExpansionUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . - /// - /// A CoefficientOfThermalExpansion with the specified unit. - public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new CoefficientOfThermalExpansion(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return _value; - case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return _value * 9 / 5; - case CoefficientOfThermalExpansionUnit.InverseKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(CoefficientOfThermalExpansionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case CoefficientOfThermalExpansionUnit.InverseDegreeCelsius: return baseUnitValue; - case CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit: return baseUnitValue * 5 / 9; - case CoefficientOfThermalExpansionUnit.InverseKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Compressibility.g.cs deleted file mode 100644 index ded50f06aa..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Compressibility.g.cs +++ /dev/null @@ -1,707 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Compressibility is the measure of the relative volume change of a fluid or solid in response to pressure changes. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Compressibility : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly CompressibilityUnit? _unit; - - static Compressibility() - { - BaseDimensions = new BaseDimensions(1, -1, 2, 0, 0, 0, 0); - BaseUnit = CompressibilityUnit.InversePascal; - MaxValue = new Compressibility(double.MaxValue, BaseUnit); - MinValue = new Compressibility(double.MinValue, BaseUnit); - QuantityType = QuantityType.Compressibility; - Units = Enum.GetValues(typeof(CompressibilityUnit)).Cast().Except(new CompressibilityUnit[]{ CompressibilityUnit.Undefined }).ToArray(); - Zero = new Compressibility(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Compressibility, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit InversePascal. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Compressibility() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Compressibility(double value, CompressibilityUnit unit) - { - if (unit == CompressibilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Compressibility, which is InversePascal. All conversions go via this value. - /// - public static CompressibilityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Compressibility - /// - public static Compressibility MaxValue { get; } - - /// - /// Represents the smallest possible value of Compressibility - /// - public static Compressibility MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Compressibility quantity. - /// - public static CompressibilityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InversePascal. - /// - public static Compressibility Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public CompressibilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Compressibility.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Compressibility.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double InverseAtmospheres => As(CompressibilityUnit.InverseAtmosphere); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseBars => As(CompressibilityUnit.InverseBar); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseKilopascals => As(CompressibilityUnit.InverseKilopascal); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMegapascals => As(CompressibilityUnit.InverseMegapascal); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMillibars => As(CompressibilityUnit.InverseMillibar); - - /// - /// Gets a value of this quantity converted into - /// - public double InversePascals => As(CompressibilityUnit.InversePascal); - - /// - /// Gets a value of this quantity converted into - /// - public double InversePoundsForcePerSquareInch => As(CompressibilityUnit.InversePoundForcePerSquareInch); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(CompressibilityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(CompressibilityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInverseAtmospheres(double inverseatmospheres) - { - double value = (double) inverseatmospheres; - return new Compressibility(value, CompressibilityUnit.InverseAtmosphere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInverseBars(double inversebars) - { - double value = (double) inversebars; - return new Compressibility(value, CompressibilityUnit.InverseBar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInverseKilopascals(double inversekilopascals) - { - double value = (double) inversekilopascals; - return new Compressibility(value, CompressibilityUnit.InverseKilopascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInverseMegapascals(double inversemegapascals) - { - double value = (double) inversemegapascals; - return new Compressibility(value, CompressibilityUnit.InverseMegapascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInverseMillibars(double inversemillibars) - { - double value = (double) inversemillibars; - return new Compressibility(value, CompressibilityUnit.InverseMillibar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInversePascals(double inversepascals) - { - double value = (double) inversepascals; - return new Compressibility(value, CompressibilityUnit.InversePascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Compressibility FromInversePoundsForcePerSquareInch(double inversepoundsforcepersquareinch) - { - double value = (double) inversepoundsforcepersquareinch; - return new Compressibility(value, CompressibilityUnit.InversePoundForcePerSquareInch); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Compressibility unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Compressibility From(double value, CompressibilityUnit fromUnit) - { - return new Compressibility((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Compressibility Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Compressibility Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Compressibility result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Compressibility result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static CompressibilityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static CompressibilityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out CompressibilityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out CompressibilityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Compressibility objCompressibility)) throw new ArgumentException("Expected type Compressibility.", nameof(obj)); - - return CompareTo(objCompressibility); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Compressibility other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Compressibility objCompressibility)) - return false; - - return Equals(objCompressibility); - } - - public bool Equals(Compressibility other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Compressibility within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Compressibility. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((CompressibilityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CompressibilityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Compressibility to another Compressibility with the unit representation . - /// - /// A Compressibility with the specified unit. - public Compressibility ToUnit(CompressibilityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Compressibility(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case CompressibilityUnit.InverseAtmosphere: return _value * 101325; - case CompressibilityUnit.InverseBar: return _value * 1e5; - case CompressibilityUnit.InverseKilopascal: return _value * 1e3; - case CompressibilityUnit.InverseMegapascal: return _value * 1e6; - case CompressibilityUnit.InverseMillibar: return _value * 100; - case CompressibilityUnit.InversePascal: return _value; - case CompressibilityUnit.InversePoundForcePerSquareInch: return _value * 6.894757293168361e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(CompressibilityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case CompressibilityUnit.InverseAtmosphere: return baseUnitValue / 101325; - case CompressibilityUnit.InverseBar: return baseUnitValue / 1e5; - case CompressibilityUnit.InverseKilopascal: return baseUnitValue / 1e3; - case CompressibilityUnit.InverseMegapascal: return baseUnitValue / 1e6; - case CompressibilityUnit.InverseMillibar: return baseUnitValue / 100; - case CompressibilityUnit.InversePascal: return baseUnitValue; - case CompressibilityUnit.InversePoundForcePerSquareInch: return baseUnitValue / 6.894757293168361e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.g.cs deleted file mode 100644 index bc158b4a56..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Density.g.cs +++ /dev/null @@ -1,1550 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. - /// - /// - /// http://en.wikipedia.org/wiki/Density - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Density : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DensityUnit? _unit; - - static Density() - { - BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); - BaseUnit = DensityUnit.KilogramPerCubicMeter; - MaxValue = new Density(double.MaxValue, BaseUnit); - MinValue = new Density(double.MinValue, BaseUnit); - QuantityType = QuantityType.Density; - Units = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); - Zero = new Density(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Density, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerCubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Density() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Density(double value, DensityUnit unit) - { - if (unit == DensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. - /// - public static DensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Density - /// - public static Density MaxValue { get; } - - /// - /// Represents the smallest possible value of Density - /// - public static Density MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Density quantity. - /// - public static DensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. - /// - public static Density Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Density.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Density.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicFoot => As(DensityUnit.GramPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicInch => As(DensityUnit.GramPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerLiter => As(DensityUnit.GramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerLiter => As(DensityUnit.KilogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerCubicMeter => As(DensityUnit.MicrogramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicCentimeter => As(DensityUnit.PoundPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicMeter => As(DensityUnit.PoundPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicMillimeter => As(DensityUnit.PoundPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugsPerCubicCentimeter => As(DensityUnit.SlugPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugsPerCubicInch => As(DensityUnit.SlugPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugsPerCubicMeter => As(DensityUnit.SlugPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugsPerCubicMillimeter => As(DensityUnit.SlugPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicFoot => As(DensityUnit.TonnePerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicInch => As(DensityUnit.TonnePerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); - - #endregion - - #region Static Methods - - 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³"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(DensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(DensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerDeciLiter(double centigramsperdeciliter) - { - double value = (double) centigramsperdeciliter; - return new Density(value, DensityUnit.CentigramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerLiter(double centigramsperliter) - { - double value = (double) centigramsperliter; - return new Density(value, DensityUnit.CentigramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromCentigramsPerMilliliter(double centigramspermilliliter) - { - double value = (double) centigramspermilliliter; - return new Density(value, DensityUnit.CentigramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerDeciLiter(double decigramsperdeciliter) - { - double value = (double) decigramsperdeciliter; - return new Density(value, DensityUnit.DecigramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerLiter(double decigramsperliter) - { - double value = (double) decigramsperliter; - return new Density(value, DensityUnit.DecigramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromDecigramsPerMilliliter(double decigramspermilliliter) - { - double value = (double) decigramspermilliliter; - return new Density(value, DensityUnit.DecigramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicCentimeter(double gramspercubiccentimeter) - { - double value = (double) gramspercubiccentimeter; - return new Density(value, DensityUnit.GramPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicFoot(double gramspercubicfoot) - { - double value = (double) gramspercubicfoot; - return new Density(value, DensityUnit.GramPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicInch(double gramspercubicinch) - { - double value = (double) gramspercubicinch; - return new Density(value, DensityUnit.GramPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicMeter(double gramspercubicmeter) - { - double value = (double) gramspercubicmeter; - return new Density(value, DensityUnit.GramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerCubicMillimeter(double gramspercubicmillimeter) - { - double value = (double) gramspercubicmillimeter; - return new Density(value, DensityUnit.GramPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerDeciLiter(double gramsperdeciliter) - { - double value = (double) gramsperdeciliter; - return new Density(value, DensityUnit.GramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerLiter(double gramsperliter) - { - double value = (double) gramsperliter; - return new Density(value, DensityUnit.GramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromGramsPerMilliliter(double gramspermilliliter) - { - double value = (double) gramspermilliliter; - return new Density(value, DensityUnit.GramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) - { - double value = (double) kilogramspercubiccentimeter; - return new Density(value, DensityUnit.KilogramPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicMeter(double kilogramspercubicmeter) - { - double value = (double) kilogramspercubicmeter; - return new Density(value, DensityUnit.KilogramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) - { - double value = (double) kilogramspercubicmillimeter; - return new Density(value, DensityUnit.KilogramPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilogramsPerLiter(double kilogramsperliter) - { - double value = (double) kilogramsperliter; - return new Density(value, DensityUnit.KilogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) - { - double value = (double) kilopoundspercubicfoot; - return new Density(value, DensityUnit.KilopoundPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromKilopoundsPerCubicInch(double kilopoundspercubicinch) - { - double value = (double) kilopoundspercubicinch; - return new Density(value, DensityUnit.KilopoundPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerCubicMeter(double microgramspercubicmeter) - { - double value = (double) microgramspercubicmeter; - return new Density(value, DensityUnit.MicrogramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerDeciLiter(double microgramsperdeciliter) - { - double value = (double) microgramsperdeciliter; - return new Density(value, DensityUnit.MicrogramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerLiter(double microgramsperliter) - { - double value = (double) microgramsperliter; - return new Density(value, DensityUnit.MicrogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMicrogramsPerMilliliter(double microgramspermilliliter) - { - double value = (double) microgramspermilliliter; - return new Density(value, DensityUnit.MicrogramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerCubicMeter(double milligramspercubicmeter) - { - double value = (double) milligramspercubicmeter; - return new Density(value, DensityUnit.MilligramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerDeciLiter(double milligramsperdeciliter) - { - double value = (double) milligramsperdeciliter; - return new Density(value, DensityUnit.MilligramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerLiter(double milligramsperliter) - { - double value = (double) milligramsperliter; - return new Density(value, DensityUnit.MilligramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromMilligramsPerMilliliter(double milligramspermilliliter) - { - double value = (double) milligramspermilliliter; - return new Density(value, DensityUnit.MilligramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerDeciLiter(double nanogramsperdeciliter) - { - double value = (double) nanogramsperdeciliter; - return new Density(value, DensityUnit.NanogramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerLiter(double nanogramsperliter) - { - double value = (double) nanogramsperliter; - return new Density(value, DensityUnit.NanogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromNanogramsPerMilliliter(double nanogramspermilliliter) - { - double value = (double) nanogramspermilliliter; - return new Density(value, DensityUnit.NanogramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerDeciLiter(double picogramsperdeciliter) - { - double value = (double) picogramsperdeciliter; - return new Density(value, DensityUnit.PicogramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerLiter(double picogramsperliter) - { - double value = (double) picogramsperliter; - return new Density(value, DensityUnit.PicogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPicogramsPerMilliliter(double picogramspermilliliter) - { - double value = (double) picogramspermilliliter; - return new Density(value, DensityUnit.PicogramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicCentimeter(double poundspercubiccentimeter) - { - double value = (double) poundspercubiccentimeter; - return new Density(value, DensityUnit.PoundPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicFoot(double poundspercubicfoot) - { - double value = (double) poundspercubicfoot; - return new Density(value, DensityUnit.PoundPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicInch(double poundspercubicinch) - { - double value = (double) poundspercubicinch; - return new Density(value, DensityUnit.PoundPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicMeter(double poundspercubicmeter) - { - double value = (double) poundspercubicmeter; - return new Density(value, DensityUnit.PoundPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerCubicMillimeter(double poundspercubicmillimeter) - { - double value = (double) poundspercubicmillimeter; - return new Density(value, DensityUnit.PoundPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerImperialGallon(double poundsperimperialgallon) - { - double value = (double) poundsperimperialgallon; - return new Density(value, DensityUnit.PoundPerImperialGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromPoundsPerUSGallon(double poundsperusgallon) - { - double value = (double) poundsperusgallon; - return new Density(value, DensityUnit.PoundPerUSGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicCentimeter(double slugspercubiccentimeter) - { - double value = (double) slugspercubiccentimeter; - return new Density(value, DensityUnit.SlugPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicFoot(double slugspercubicfoot) - { - double value = (double) slugspercubicfoot; - return new Density(value, DensityUnit.SlugPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicInch(double slugspercubicinch) - { - double value = (double) slugspercubicinch; - return new Density(value, DensityUnit.SlugPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicMeter(double slugspercubicmeter) - { - double value = (double) slugspercubicmeter; - return new Density(value, DensityUnit.SlugPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromSlugsPerCubicMillimeter(double slugspercubicmillimeter) - { - double value = (double) slugspercubicmillimeter; - return new Density(value, DensityUnit.SlugPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) - { - double value = (double) tonnespercubiccentimeter; - return new Density(value, DensityUnit.TonnePerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicFoot(double tonnespercubicfoot) - { - double value = (double) tonnespercubicfoot; - return new Density(value, DensityUnit.TonnePerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicInch(double tonnespercubicinch) - { - double value = (double) tonnespercubicinch; - return new Density(value, DensityUnit.TonnePerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicMeter(double tonnespercubicmeter) - { - double value = (double) tonnespercubicmeter; - return new Density(value, DensityUnit.TonnePerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Density FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) - { - double value = (double) tonnespercubicmillimeter; - return new Density(value, DensityUnit.TonnePerCubicMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Density unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Density From(double value, DensityUnit fromUnit) - { - return new Density((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Density Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Density Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Density result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Density result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out DensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out DensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Density objDensity)) throw new ArgumentException("Expected type Density.", nameof(obj)); - - return CompareTo(objDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Density other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Density objDensity)) - return false; - - return Equals(objDensity); - } - - public bool Equals(Density other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Density within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Density other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Density. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((DensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Density to another Density with the unit representation . - /// - /// A Density with the specified unit. - public Density ToUnit(DensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Density(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case DensityUnit.CentigramPerDeciliter: return (_value / 1e-1) * 1e-2d; - case DensityUnit.CentigramPerLiter: return (_value / 1) * 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (_value / 1e-3) * 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (_value / 1e-1) * 1e-1d; - case DensityUnit.DecigramPerLiter: return (_value / 1) * 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (_value / 1e-3) * 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return _value / 1e-3; - case DensityUnit.GramPerCubicFoot: return _value * 0.0353146667214886; - case DensityUnit.GramPerCubicInch: return _value * 61.0237440947323; - case DensityUnit.GramPerCubicMeter: return _value / 1e3; - case DensityUnit.GramPerCubicMillimeter: return _value / 1e-6; - case DensityUnit.GramPerDeciliter: return _value / 1e-1; - case DensityUnit.GramPerLiter: return _value / 1; - case DensityUnit.GramPerMilliliter: return _value / 1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (_value / 1e-3) * 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (_value / 1e3) * 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (_value / 1e-6) * 1e3d; - case DensityUnit.KilogramPerLiter: return _value * 1e3; - case DensityUnit.KilopoundPerCubicFoot: return (_value / 0.062427961) * 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (_value / 3.6127298147753e-5) * 1e3d; - case DensityUnit.MicrogramPerCubicMeter: return (_value / 1e3) * 1e-6d; - case DensityUnit.MicrogramPerDeciliter: return (_value / 1e-1) * 1e-6d; - case DensityUnit.MicrogramPerLiter: return (_value / 1) * 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (_value / 1e-3) * 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (_value / 1e3) * 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (_value / 1e-1) * 1e-3d; - case DensityUnit.MilligramPerLiter: return (_value / 1) * 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (_value / 1e-3) * 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (_value / 1e-1) * 1e-9d; - case DensityUnit.NanogramPerLiter: return (_value / 1) * 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (_value / 1e-3) * 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (_value / 1e-1) * 1e-12d; - case DensityUnit.PicogramPerLiter: return (_value / 1) * 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (_value / 1e-3) * 1e-12d; - case DensityUnit.PoundPerCubicCentimeter: return _value / 2.204622621848775e-6; - case DensityUnit.PoundPerCubicFoot: return _value / 0.062427961; - case DensityUnit.PoundPerCubicInch: return _value / 3.6127298147753e-5; - case DensityUnit.PoundPerCubicMeter: return _value / 2.204622621848775; - case DensityUnit.PoundPerCubicMillimeter: return _value / 2.204622621848775e-9; - case DensityUnit.PoundPerImperialGallon: return _value * 9.9776398e1; - case DensityUnit.PoundPerUSGallon: return _value * 1.19826427e2; - case DensityUnit.SlugPerCubicCentimeter: return _value * 14593903; - case DensityUnit.SlugPerCubicFoot: return _value * 515.378818; - case DensityUnit.SlugPerCubicInch: return _value * 890574.60201535; - case DensityUnit.SlugPerCubicMeter: return _value * 14.5939; - case DensityUnit.SlugPerCubicMillimeter: return _value * 14593903000; - case DensityUnit.TonnePerCubicCentimeter: return _value / 1e-9; - case DensityUnit.TonnePerCubicFoot: return _value * 3.53146667214886e4; - case DensityUnit.TonnePerCubicInch: return _value * 6.10237440947323e7; - case DensityUnit.TonnePerCubicMeter: return _value / 0.001; - case DensityUnit.TonnePerCubicMillimeter: return _value / 1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DensityUnit.CentigramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-2d; - case DensityUnit.CentigramPerLiter: return (baseUnitValue * 1) / 1e-2d; - case DensityUnit.CentigramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-2d; - case DensityUnit.DecigramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-1d; - case DensityUnit.DecigramPerLiter: return (baseUnitValue * 1) / 1e-1d; - case DensityUnit.DecigramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-1d; - case DensityUnit.GramPerCubicCentimeter: return baseUnitValue * 1e-3; - case DensityUnit.GramPerCubicFoot: return baseUnitValue / 0.0353146667214886; - case DensityUnit.GramPerCubicInch: return baseUnitValue / 61.0237440947323; - case DensityUnit.GramPerCubicMeter: return baseUnitValue * 1e3; - case DensityUnit.GramPerCubicMillimeter: return baseUnitValue * 1e-6; - case DensityUnit.GramPerDeciliter: return baseUnitValue * 1e-1; - case DensityUnit.GramPerLiter: return baseUnitValue * 1; - case DensityUnit.GramPerMilliliter: return baseUnitValue * 1e-3; - case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue * 1e-3) / 1e3d; - case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue * 1e3) / 1e3d; - case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue * 1e-6) / 1e3d; - case DensityUnit.KilogramPerLiter: return baseUnitValue / 1e3; - case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue * 0.062427961) / 1e3d; - case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue * 3.6127298147753e-5) / 1e3d; - case DensityUnit.MicrogramPerCubicMeter: return (baseUnitValue * 1e3) / 1e-6d; - case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-6d; - case DensityUnit.MicrogramPerLiter: return (baseUnitValue * 1) / 1e-6d; - case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-6d; - case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue * 1e3) / 1e-3d; - case DensityUnit.MilligramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-3d; - case DensityUnit.MilligramPerLiter: return (baseUnitValue * 1) / 1e-3d; - case DensityUnit.MilligramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-3d; - case DensityUnit.NanogramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-9d; - case DensityUnit.NanogramPerLiter: return (baseUnitValue * 1) / 1e-9d; - case DensityUnit.NanogramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-9d; - case DensityUnit.PicogramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-12d; - case DensityUnit.PicogramPerLiter: return (baseUnitValue * 1) / 1e-12d; - case DensityUnit.PicogramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-12d; - case DensityUnit.PoundPerCubicCentimeter: return baseUnitValue * 2.204622621848775e-6; - case DensityUnit.PoundPerCubicFoot: return baseUnitValue * 0.062427961; - case DensityUnit.PoundPerCubicInch: return baseUnitValue * 3.6127298147753e-5; - case DensityUnit.PoundPerCubicMeter: return baseUnitValue * 2.204622621848775; - case DensityUnit.PoundPerCubicMillimeter: return baseUnitValue * 2.204622621848775e-9; - case DensityUnit.PoundPerImperialGallon: return baseUnitValue / 9.9776398e1; - case DensityUnit.PoundPerUSGallon: return baseUnitValue / 1.19826427e2; - case DensityUnit.SlugPerCubicCentimeter: return baseUnitValue / 14593903; - case DensityUnit.SlugPerCubicFoot: return baseUnitValue * 0.00194032033; - case DensityUnit.SlugPerCubicInch: return baseUnitValue / 890574.60201535; - case DensityUnit.SlugPerCubicMeter: return baseUnitValue / 14.5939; - case DensityUnit.SlugPerCubicMillimeter: return baseUnitValue / 14593903000; - case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue * 1e-9; - case DensityUnit.TonnePerCubicFoot: return baseUnitValue / 3.53146667214886e4; - case DensityUnit.TonnePerCubicInch: return baseUnitValue / 6.10237440947323e7; - case DensityUnit.TonnePerCubicMeter: return baseUnitValue * 0.001; - case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue * 1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.g.cs deleted file mode 100644 index ff21b61a61..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Duration.g.cs +++ /dev/null @@ -1,793 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Duration : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DurationUnit? _unit; - - static Duration() - { - BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); - BaseUnit = DurationUnit.Second; - MaxValue = new Duration(double.MaxValue, BaseUnit); - MinValue = new Duration(double.MinValue, BaseUnit); - QuantityType = QuantityType.Duration; - Units = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); - Zero = new Duration(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Duration, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Second. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Duration() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Duration(double value, DurationUnit unit) - { - if (unit == DurationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Duration, which is Second. All conversions go via this value. - /// - public static DurationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Duration - /// - public static Duration MaxValue { get; } - - /// - /// Represents the smallest possible value of Duration - /// - public static Duration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Duration quantity. - /// - public static DurationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Second. - /// - public static Duration Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Duration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Duration.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Days => As(DurationUnit.Day); - - /// - /// Gets a value of this quantity converted into - /// - public double Hours => As(DurationUnit.Hour); - - /// - /// Gets a value of this quantity converted into - /// - public double JulianYears => As(DurationUnit.JulianYear); - - /// - /// Gets a value of this quantity converted into - /// - public double Microseconds => As(DurationUnit.Microsecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliseconds => As(DurationUnit.Millisecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Minutes => As(DurationUnit.Minute); - - /// - /// Gets a value of this quantity converted into - /// - public double Months30 => As(DurationUnit.Month30); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanoseconds => As(DurationUnit.Nanosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Seconds => As(DurationUnit.Second); - - /// - /// Gets a value of this quantity converted into - /// - public double Weeks => As(DurationUnit.Week); - - /// - /// Gets a value of this quantity converted into - /// - public double Years365 => As(DurationUnit.Year365); - - #endregion - - #region Static Methods - - 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[]{"год"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(DurationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(DurationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromDays(double days) - { - double value = (double) days; - return new Duration(value, DurationUnit.Day); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromHours(double hours) - { - double value = (double) hours; - return new Duration(value, DurationUnit.Hour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromJulianYears(double julianyears) - { - double value = (double) julianyears; - return new Duration(value, DurationUnit.JulianYear); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMicroseconds(double microseconds) - { - double value = (double) microseconds; - return new Duration(value, DurationUnit.Microsecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMilliseconds(double milliseconds) - { - double value = (double) milliseconds; - return new Duration(value, DurationUnit.Millisecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMinutes(double minutes) - { - double value = (double) minutes; - return new Duration(value, DurationUnit.Minute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromMonths30(double months30) - { - double value = (double) months30; - return new Duration(value, DurationUnit.Month30); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromNanoseconds(double nanoseconds) - { - double value = (double) nanoseconds; - return new Duration(value, DurationUnit.Nanosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromSeconds(double seconds) - { - double value = (double) seconds; - return new Duration(value, DurationUnit.Second); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromWeeks(double weeks) - { - double value = (double) weeks; - return new Duration(value, DurationUnit.Week); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Duration FromYears365(double years365) - { - double value = (double) years365; - return new Duration(value, DurationUnit.Year365); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Duration unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Duration From(double value, DurationUnit fromUnit) - { - return new Duration((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Duration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Duration Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Duration result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Duration result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DurationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out DurationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out DurationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Duration objDuration)) throw new ArgumentException("Expected type Duration.", nameof(obj)); - - return CompareTo(objDuration); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Duration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Duration objDuration)) - return false; - - return Equals(objDuration); - } - - public bool Equals(Duration other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Duration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Duration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Duration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((DurationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DurationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// A Duration with the specified unit. - public Duration ToUnit(DurationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Duration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case DurationUnit.Day: return _value * 24 * 3600; - case DurationUnit.Hour: return _value * 3600; - case DurationUnit.JulianYear: return _value * 365.25 * 24 * 3600; - case DurationUnit.Microsecond: return (_value) * 1e-6d; - case DurationUnit.Millisecond: return (_value) * 1e-3d; - case DurationUnit.Minute: return _value * 60; - case DurationUnit.Month30: return _value * 30 * 24 * 3600; - case DurationUnit.Nanosecond: return (_value) * 1e-9d; - case DurationUnit.Second: return _value; - case DurationUnit.Week: return _value * 7 * 24 * 3600; - case DurationUnit.Year365: return _value * 365 * 24 * 3600; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DurationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DurationUnit.Day: return baseUnitValue / (24 * 3600); - case DurationUnit.Hour: return baseUnitValue / 3600; - case DurationUnit.JulianYear: return baseUnitValue / (365.25 * 24 * 3600); - case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; - case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; - case DurationUnit.Minute: return baseUnitValue / 60; - case DurationUnit.Month30: return baseUnitValue / (30 * 24 * 3600); - case DurationUnit.Nanosecond: return (baseUnitValue) / 1e-9d; - case DurationUnit.Second: return baseUnitValue; - case DurationUnit.Week: return baseUnitValue / (7 * 24 * 3600); - case DurationUnit.Year365: return baseUnitValue / (365 * 24 * 3600); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.g.cs deleted file mode 100644 index 8c586609aa..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ /dev/null @@ -1,767 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds - /// - /// - /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class DynamicViscosity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly DynamicViscosityUnit? _unit; - - static DynamicViscosity() - { - BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); - BaseUnit = DynamicViscosityUnit.NewtonSecondPerMeterSquared; - MaxValue = new DynamicViscosity(double.MaxValue, BaseUnit); - MinValue = new DynamicViscosity(double.MinValue, BaseUnit); - QuantityType = QuantityType.DynamicViscosity; - Units = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); - Zero = new DynamicViscosity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.DynamicViscosity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public DynamicViscosity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private DynamicViscosity(double value, DynamicViscosityUnit unit) - { - if (unit == DynamicViscosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. - /// - public static DynamicViscosityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of DynamicViscosity - /// - public static DynamicViscosity MaxValue { get; } - - /// - /// Represents the smallest possible value of DynamicViscosity - /// - public static DynamicViscosity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the DynamicViscosity quantity. - /// - public static DynamicViscosityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. - /// - public static DynamicViscosity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => DynamicViscosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Centipoise => As(DynamicViscosityUnit.Centipoise); - - /// - /// Gets a value of this quantity converted into - /// - public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Poise => As(DynamicViscosityUnit.Poise); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForceSecondPerSquareFoot => As(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForceSecondPerSquareInch => As(DynamicViscosityUnit.PoundForceSecondPerSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerFootSecond => As(DynamicViscosityUnit.PoundPerFootSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Reyns => As(DynamicViscosityUnit.Reyn); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(DynamicViscosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromCentipoise(double centipoise) - { - double value = (double) centipoise; - return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromMicropascalSeconds(double micropascalseconds) - { - double value = (double) micropascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromMillipascalSeconds(double millipascalseconds) - { - double value = (double) millipascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double newtonsecondspermetersquared) - { - double value = (double) newtonsecondspermetersquared; - return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPascalSeconds(double pascalseconds) - { - double value = (double) pascalseconds; - return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPoise(double poise) - { - double value = (double) poise; - return new DynamicViscosity(value, DynamicViscosityUnit.Poise); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(double poundsforcesecondpersquarefoot) - { - double value = (double) poundsforcesecondpersquarefoot; - return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPoundsForceSecondPerSquareInch(double poundsforcesecondpersquareinch) - { - double value = (double) poundsforcesecondpersquareinch; - return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromPoundsPerFootSecond(double poundsperfootsecond) - { - double value = (double) poundsperfootsecond; - return new DynamicViscosity(value, DynamicViscosityUnit.PoundPerFootSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static DynamicViscosity FromReyns(double reyns) - { - double value = (double) reyns; - return new DynamicViscosity(value, DynamicViscosityUnit.Reyn); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// DynamicViscosity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) - { - return new DynamicViscosity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static DynamicViscosity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static DynamicViscosity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out DynamicViscosity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static DynamicViscosityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out DynamicViscosityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is DynamicViscosity objDynamicViscosity)) throw new ArgumentException("Expected type DynamicViscosity.", nameof(obj)); - - return CompareTo(objDynamicViscosity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(DynamicViscosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is DynamicViscosity objDynamicViscosity)) - return false; - - return Equals(objDynamicViscosity); - } - - public bool Equals(DynamicViscosity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another DynamicViscosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current DynamicViscosity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((DynamicViscosityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DynamicViscosityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . - /// - /// A DynamicViscosity with the specified unit. - public DynamicViscosity ToUnit(DynamicViscosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new DynamicViscosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case DynamicViscosityUnit.Centipoise: return (_value / 10) * 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; - case DynamicViscosityUnit.PascalSecond: return _value; - case DynamicViscosityUnit.Poise: return _value / 10; - case DynamicViscosityUnit.PoundForceSecondPerSquareFoot: return _value * 4.7880258980335843e1; - case DynamicViscosityUnit.PoundForceSecondPerSquareInch: return _value * 6.8947572931683613e3; - case DynamicViscosityUnit.PoundPerFootSecond: return _value * 1.4881639; - case DynamicViscosityUnit.Reyn: return _value * 6.8947572931683613e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(DynamicViscosityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case DynamicViscosityUnit.Centipoise: return (baseUnitValue * 10) / 1e-2d; - case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; - case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; - case DynamicViscosityUnit.PascalSecond: return baseUnitValue; - case DynamicViscosityUnit.Poise: return baseUnitValue * 10; - case DynamicViscosityUnit.PoundForceSecondPerSquareFoot: return baseUnitValue / 4.7880258980335843e1; - case DynamicViscosityUnit.PoundForceSecondPerSquareInch: return baseUnitValue / 6.8947572931683613e3; - case DynamicViscosityUnit.PoundPerFootSecond: return baseUnitValue / 1.4881639; - case DynamicViscosityUnit.Reyn: return baseUnitValue / 6.8947572931683613e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.g.cs deleted file mode 100644 index e34f733af6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricAdmittance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricAdmittanceUnit? _unit; - - static ElectricAdmittance() - { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricAdmittanceUnit.Siemens; - MaxValue = new ElectricAdmittance(double.MaxValue, BaseUnit); - MinValue = new ElectricAdmittance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricAdmittance; - Units = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); - Zero = new ElectricAdmittance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricAdmittance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Siemens. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricAdmittance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricAdmittance(double value, ElectricAdmittanceUnit unit) - { - if (unit == ElectricAdmittanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. - /// - public static ElectricAdmittanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricAdmittance - /// - public static ElectricAdmittance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricAdmittance - /// - public static ElectricAdmittance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricAdmittance quantity. - /// - public static ElectricAdmittanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. - /// - public static ElectricAdmittance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricAdmittance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); - - /// - /// Gets a value of this quantity converted into - /// - public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); - - /// - /// Gets a value of this quantity converted into - /// - public double Siemens => As(ElectricAdmittanceUnit.Siemens); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricAdmittanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromMicrosiemens(double microsiemens) - { - double value = (double) microsiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromMillisiemens(double millisiemens) - { - double value = (double) millisiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromNanosiemens(double nanosiemens) - { - double value = (double) nanosiemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricAdmittance FromSiemens(double siemens) - { - double value = (double) siemens; - return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricAdmittance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromUnit) - { - return new ElectricAdmittance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricAdmittance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricAdmittance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricAdmittance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricAdmittance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricAdmittanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricAdmittanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricAdmittance objElectricAdmittance)) throw new ArgumentException("Expected type ElectricAdmittance.", nameof(obj)); - - return CompareTo(objElectricAdmittance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricAdmittance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricAdmittance objElectricAdmittance)) - return false; - - return Equals(objElectricAdmittance); - } - - public bool Equals(ElectricAdmittance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricAdmittance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricAdmittance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricAdmittanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricAdmittanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . - /// - /// A ElectricAdmittance with the specified unit. - public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricAdmittance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (_value) * 1e-9d; - case ElectricAdmittanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricAdmittanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricAdmittanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricAdmittanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricAdmittanceUnit.Nanosiemens: return (baseUnitValue) / 1e-9d; - case ElectricAdmittanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.g.cs deleted file mode 100644 index 30b6436728..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCharge.g.cs +++ /dev/null @@ -1,672 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field. - /// - /// - /// https://en.wikipedia.org/wiki/Electric_charge - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricCharge : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricChargeUnit? _unit; - - static ElectricCharge() - { - BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); - BaseUnit = ElectricChargeUnit.Coulomb; - MaxValue = new ElectricCharge(double.MaxValue, BaseUnit); - MinValue = new ElectricCharge(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCharge; - Units = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); - Zero = new ElectricCharge(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricCharge, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Coulomb. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricCharge() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricCharge(double value, ElectricChargeUnit unit) - { - if (unit == ElectricChargeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. - /// - public static ElectricChargeUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricCharge - /// - public static ElectricCharge MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCharge - /// - public static ElectricCharge MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricCharge quantity. - /// - public static ElectricChargeUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. - /// - public static ElectricCharge Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricCharge.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AmpereHours => As(ElectricChargeUnit.AmpereHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Coulombs => As(ElectricChargeUnit.Coulomb); - - /// - /// Gets a value of this quantity converted into - /// - public double KiloampereHours => As(ElectricChargeUnit.KiloampereHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegaampereHours => As(ElectricChargeUnit.MegaampereHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliampereHours => As(ElectricChargeUnit.MilliampereHour); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricChargeUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromAmpereHours(double amperehours) - { - double value = (double) amperehours; - return new ElectricCharge(value, ElectricChargeUnit.AmpereHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromCoulombs(double coulombs) - { - double value = (double) coulombs; - return new ElectricCharge(value, ElectricChargeUnit.Coulomb); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromKiloampereHours(double kiloamperehours) - { - double value = (double) kiloamperehours; - return new ElectricCharge(value, ElectricChargeUnit.KiloampereHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromMegaampereHours(double megaamperehours) - { - double value = (double) megaamperehours; - return new ElectricCharge(value, ElectricChargeUnit.MegaampereHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCharge FromMilliampereHours(double milliamperehours) - { - double value = (double) milliamperehours; - return new ElectricCharge(value, ElectricChargeUnit.MilliampereHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCharge unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) - { - return new ElectricCharge((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCharge Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCharge Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCharge result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricCharge result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricChargeUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricChargeUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCharge objElectricCharge)) throw new ArgumentException("Expected type ElectricCharge.", nameof(obj)); - - return CompareTo(objElectricCharge); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricCharge other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCharge objElectricCharge)) - return false; - - return Equals(objElectricCharge); - } - - public bool Equals(ElectricCharge other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCharge within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCharge other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCharge. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricChargeUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCharge to another ElectricCharge with the unit representation . - /// - /// A ElectricCharge with the specified unit. - public ElectricCharge ToUnit(ElectricChargeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCharge(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricChargeUnit.AmpereHour: return _value / 2.77777777777e-4; - case ElectricChargeUnit.Coulomb: return _value; - case ElectricChargeUnit.KiloampereHour: return (_value / 2.77777777777e-4) * 1e3d; - case ElectricChargeUnit.MegaampereHour: return (_value / 2.77777777777e-4) * 1e6d; - case ElectricChargeUnit.MilliampereHour: return (_value / 2.77777777777e-4) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricChargeUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricChargeUnit.AmpereHour: return baseUnitValue * 2.77777777777e-4; - case ElectricChargeUnit.Coulomb: return baseUnitValue; - case ElectricChargeUnit.KiloampereHour: return (baseUnitValue * 2.77777777777e-4) / 1e3d; - case ElectricChargeUnit.MegaampereHour: return (baseUnitValue * 2.77777777777e-4) / 1e6d; - case ElectricChargeUnit.MilliampereHour: return (baseUnitValue * 2.77777777777e-4) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.g.cs deleted file mode 100644 index 8b4670fdd3..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, charge density is a measure of the amount of electric charge per volume. - /// - /// - /// https://en.wikipedia.org/wiki/Charge_density - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricChargeDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricChargeDensityUnit? _unit; - - static ElectricChargeDensity() - { - BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); - BaseUnit = ElectricChargeDensityUnit.CoulombPerCubicMeter; - MaxValue = new ElectricChargeDensity(double.MaxValue, BaseUnit); - MinValue = new ElectricChargeDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricChargeDensity; - Units = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); - Zero = new ElectricChargeDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricChargeDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CoulombPerCubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricChargeDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricChargeDensity(double value, ElectricChargeDensityUnit unit) - { - if (unit == ElectricChargeDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. - /// - public static ElectricChargeDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricChargeDensity - /// - public static ElectricChargeDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricChargeDensity - /// - public static ElectricChargeDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricChargeDensity quantity. - /// - public static ElectricChargeDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. - /// - public static ElectricChargeDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricChargeDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeDensityUnit.CoulombPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"C/m³"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricChargeDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricChargeDensity FromCoulombsPerCubicMeter(double coulombspercubicmeter) - { - double value = (double) coulombspercubicmeter; - return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricChargeDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit fromUnit) - { - return new ElectricChargeDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricChargeDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricChargeDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricChargeDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricChargeDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricChargeDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricChargeDensity objElectricChargeDensity)) throw new ArgumentException("Expected type ElectricChargeDensity.", nameof(obj)); - - return CompareTo(objElectricChargeDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricChargeDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricChargeDensity objElectricChargeDensity)) - return false; - - return Equals(objElectricChargeDensity); - } - - public bool Equals(ElectricChargeDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricChargeDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricChargeDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricChargeDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation . - /// - /// A ElectricChargeDensity with the specified unit. - public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricChargeDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricChargeDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.g.cs deleted file mode 100644 index 035885ba00..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductance.g.cs +++ /dev/null @@ -1,634 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor. - /// - /// - /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricConductance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricConductanceUnit? _unit; - - static ElectricConductance() - { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricConductanceUnit.Siemens; - MaxValue = new ElectricConductance(double.MaxValue, BaseUnit); - MinValue = new ElectricConductance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricConductance; - Units = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); - Zero = new ElectricConductance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricConductance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Siemens. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricConductance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricConductance(double value, ElectricConductanceUnit unit) - { - if (unit == ElectricConductanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. - /// - public static ElectricConductanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricConductance - /// - public static ElectricConductance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricConductance - /// - public static ElectricConductance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricConductance quantity. - /// - public static ElectricConductanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. - /// - public static ElectricConductance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricConductance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); - - /// - /// Gets a value of this quantity converted into - /// - public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); - - /// - /// Gets a value of this quantity converted into - /// - public double Siemens => As(ElectricConductanceUnit.Siemens); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricConductanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromMicrosiemens(double microsiemens) - { - double value = (double) microsiemens; - return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromMillisiemens(double millisiemens) - { - double value = (double) millisiemens; - return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductance FromSiemens(double siemens) - { - double value = (double) siemens; - return new ElectricConductance(value, ElectricConductanceUnit.Siemens); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricConductance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricConductance From(double value, ElectricConductanceUnit fromUnit) - { - return new ElectricConductance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricConductance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricConductance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricConductance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricConductance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricConductanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricConductance objElectricConductance)) throw new ArgumentException("Expected type ElectricConductance.", nameof(obj)); - - return CompareTo(objElectricConductance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricConductance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricConductance objElectricConductance)) - return false; - - return Equals(objElectricConductance); - } - - public bool Equals(ElectricConductance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricConductance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricConductance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricConductanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricConductance to another ElectricConductance with the unit representation . - /// - /// A ElectricConductance with the specified unit. - public ElectricConductance ToUnit(ElectricConductanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricConductance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricConductanceUnit.Microsiemens: return (_value) * 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (_value) * 1e-3d; - case ElectricConductanceUnit.Siemens: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricConductanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricConductanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; - case ElectricConductanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; - case ElectricConductanceUnit.Siemens: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.g.cs deleted file mode 100644 index 726b285d34..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ /dev/null @@ -1,691 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current. - /// - /// - /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricConductivity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricConductivityUnit? _unit; - - static ElectricConductivity() - { - BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricConductivityUnit.SiemensPerMeter; - MaxValue = new ElectricConductivity(double.MaxValue, BaseUnit); - MinValue = new ElectricConductivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricConductivity; - Units = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); - Zero = new ElectricConductivity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricConductivity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit SiemensPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricConductivity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricConductivity(double value, ElectricConductivityUnit unit) - { - if (unit == ElectricConductivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. - /// - public static ElectricConductivityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricConductivity - /// - public static ElectricConductivity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricConductivity - /// - public static ElectricConductivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricConductivity quantity. - /// - public static ElectricConductivityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. - /// - public static ElectricConductivity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricConductivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double MicrosiemensPerCentimeter => As(ElectricConductivityUnit.MicrosiemensPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillisiemensPerCentimeter => As(ElectricConductivityUnit.MillisiemensPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SiemensPerCentimeter => As(ElectricConductivityUnit.SiemensPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SiemensPerFoot => As(ElectricConductivityUnit.SiemensPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double SiemensPerInch => As(ElectricConductivityUnit.SiemensPerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricConductivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromMicrosiemensPerCentimeter(double microsiemenspercentimeter) - { - double value = (double) microsiemenspercentimeter; - return new ElectricConductivity(value, ElectricConductivityUnit.MicrosiemensPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromMillisiemensPerCentimeter(double millisiemenspercentimeter) - { - double value = (double) millisiemenspercentimeter; - return new ElectricConductivity(value, ElectricConductivityUnit.MillisiemensPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromSiemensPerCentimeter(double siemenspercentimeter) - { - double value = (double) siemenspercentimeter; - return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromSiemensPerFoot(double siemensperfoot) - { - double value = (double) siemensperfoot; - return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromSiemensPerInch(double siemensperinch) - { - double value = (double) siemensperinch; - return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricConductivity FromSiemensPerMeter(double siemenspermeter) - { - double value = (double) siemenspermeter; - return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricConductivity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricConductivity From(double value, ElectricConductivityUnit fromUnit) - { - return new ElectricConductivity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricConductivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricConductivity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricConductivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricConductivity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricConductivityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricConductivityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricConductivity objElectricConductivity)) throw new ArgumentException("Expected type ElectricConductivity.", nameof(obj)); - - return CompareTo(objElectricConductivity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricConductivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricConductivity objElectricConductivity)) - return false; - - return Equals(objElectricConductivity); - } - - public bool Equals(ElectricConductivity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricConductivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricConductivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricConductivityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductivityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation . - /// - /// A ElectricConductivity with the specified unit. - public ElectricConductivity ToUnit(ElectricConductivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricConductivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricConductivityUnit.MicrosiemensPerCentimeter: return (_value * 1e2) * 1e-6d; - case ElectricConductivityUnit.MillisiemensPerCentimeter: return (_value * 1e2) * 1e-3d; - case ElectricConductivityUnit.SiemensPerCentimeter: return _value * 1e2; - case ElectricConductivityUnit.SiemensPerFoot: return _value * 3.2808398950131234; - case ElectricConductivityUnit.SiemensPerInch: return _value * 3.937007874015748e1; - case ElectricConductivityUnit.SiemensPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricConductivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricConductivityUnit.MicrosiemensPerCentimeter: return (baseUnitValue / 1e2) / 1e-6d; - case ElectricConductivityUnit.MillisiemensPerCentimeter: return (baseUnitValue / 1e2) / 1e-3d; - case ElectricConductivityUnit.SiemensPerCentimeter: return baseUnitValue / 1e2; - case ElectricConductivityUnit.SiemensPerFoot: return baseUnitValue / 3.2808398950131234; - case ElectricConductivityUnit.SiemensPerInch: return baseUnitValue / 3.937007874015748e1; - case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.g.cs deleted file mode 100644 index 810f0c7142..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ /dev/null @@ -1,726 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricCurrent : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentUnit? _unit; - - static ElectricCurrent() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); - BaseUnit = ElectricCurrentUnit.Ampere; - MaxValue = new ElectricCurrent(double.MaxValue, BaseUnit); - MinValue = new ElectricCurrent(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCurrent; - Units = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); - Zero = new ElectricCurrent(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricCurrent, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Ampere. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricCurrent() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricCurrent(double value, ElectricCurrentUnit unit) - { - if (unit == ElectricCurrentUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. - /// - public static ElectricCurrentUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricCurrent - /// - public static ElectricCurrent MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCurrent - /// - public static ElectricCurrent MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricCurrent quantity. - /// - public static ElectricCurrentUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. - /// - public static ElectricCurrent Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricCurrent.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Amperes => As(ElectricCurrentUnit.Ampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Centiamperes => As(ElectricCurrentUnit.Centiampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Megaamperes => As(ElectricCurrentUnit.Megaampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Microamperes => As(ElectricCurrentUnit.Microampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliamperes => As(ElectricCurrentUnit.Milliampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); - - /// - /// Gets a value of this quantity converted into - /// - public double Picoamperes => As(ElectricCurrentUnit.Picoampere); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricCurrentUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromAmperes(double amperes) - { - double value = (double) amperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromCentiamperes(double centiamperes) - { - double value = (double) centiamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromKiloamperes(double kiloamperes) - { - double value = (double) kiloamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMegaamperes(double megaamperes) - { - double value = (double) megaamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMicroamperes(double microamperes) - { - double value = (double) microamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromMilliamperes(double milliamperes) - { - double value = (double) milliamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromNanoamperes(double nanoamperes) - { - double value = (double) nanoamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrent FromPicoamperes(double picoamperes) - { - double value = (double) picoamperes; - return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrent unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) - { - return new ElectricCurrent((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrent Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCurrent Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricCurrent result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricCurrentUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCurrent objElectricCurrent)) throw new ArgumentException("Expected type ElectricCurrent.", nameof(obj)); - - return CompareTo(objElectricCurrent); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricCurrent other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCurrent objElectricCurrent)) - return false; - - return Equals(objElectricCurrent); - } - - public bool Equals(ElectricCurrent other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCurrent within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrent other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrent. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricCurrentUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation . - /// - /// A ElectricCurrent with the specified unit. - public ElectricCurrent ToUnit(ElectricCurrentUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrent(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentUnit.Ampere: return _value; - case ElectricCurrentUnit.Centiampere: return (_value) * 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (_value) * 1e3d; - case ElectricCurrentUnit.Megaampere: return (_value) * 1e6d; - case ElectricCurrentUnit.Microampere: return (_value) * 1e-6d; - case ElectricCurrentUnit.Milliampere: return (_value) * 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (_value) * 1e-9d; - case ElectricCurrentUnit.Picoampere: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentUnit.Ampere: return baseUnitValue; - case ElectricCurrentUnit.Centiampere: return (baseUnitValue) / 1e-2d; - case ElectricCurrentUnit.Kiloampere: return (baseUnitValue) / 1e3d; - case ElectricCurrentUnit.Megaampere: return (baseUnitValue) / 1e6d; - case ElectricCurrentUnit.Microampere: return (baseUnitValue) / 1e-6d; - case ElectricCurrentUnit.Milliampere: return (baseUnitValue) / 1e-3d; - case ElectricCurrentUnit.Nanoampere: return (baseUnitValue) / 1e-9d; - case ElectricCurrentUnit.Picoampere: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs deleted file mode 100644 index 1f32f62f7c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ /dev/null @@ -1,634 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, current density is the electric current per unit area of cross section. - /// - /// - /// https://en.wikipedia.org/wiki/Current_density - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricCurrentDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentDensityUnit? _unit; - - static ElectricCurrentDensity() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); - BaseUnit = ElectricCurrentDensityUnit.AmperePerSquareMeter; - MaxValue = new ElectricCurrentDensity(double.MaxValue, BaseUnit); - MinValue = new ElectricCurrentDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCurrentDensity; - Units = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); - Zero = new ElectricCurrentDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricCurrentDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit AmperePerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricCurrentDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricCurrentDensity(double value, ElectricCurrentDensityUnit unit) - { - if (unit == ElectricCurrentDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. - /// - public static ElectricCurrentDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricCurrentDensity - /// - public static ElectricCurrentDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCurrentDensity - /// - public static ElectricCurrentDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricCurrentDensity quantity. - /// - public static ElectricCurrentDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. - /// - public static ElectricCurrentDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricCurrentDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerSquareFoot => As(ElectricCurrentDensityUnit.AmperePerSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerSquareInch => As(ElectricCurrentDensityUnit.AmperePerSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricCurrentDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentDensity FromAmperesPerSquareFoot(double amperespersquarefoot) - { - double value = (double) amperespersquarefoot; - return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentDensity FromAmperesPerSquareInch(double amperespersquareinch) - { - double value = (double) amperespersquareinch; - return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentDensity FromAmperesPerSquareMeter(double amperespersquaremeter) - { - double value = (double) amperespersquaremeter; - return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrentDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUnit fromUnit) - { - return new ElectricCurrentDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrentDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCurrentDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricCurrentDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricCurrentDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCurrentDensity objElectricCurrentDensity)) throw new ArgumentException("Expected type ElectricCurrentDensity.", nameof(obj)); - - return CompareTo(objElectricCurrentDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricCurrentDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCurrentDensity objElectricCurrentDensity)) - return false; - - return Equals(objElectricCurrentDensity); - } - - public bool Equals(ElectricCurrentDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCurrentDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricCurrentDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation . - /// - /// A ElectricCurrentDensity with the specified unit. - public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrentDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareFoot: return _value * 1.0763910416709722e1; - case ElectricCurrentDensityUnit.AmperePerSquareInch: return _value * 1.5500031000062000e3; - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentDensityUnit.AmperePerSquareFoot: return baseUnitValue / 1.0763910416709722e1; - case ElectricCurrentDensityUnit.AmperePerSquareInch: return baseUnitValue / 1.5500031000062000e3; - case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs deleted file mode 100644 index 4d47e289c4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, the current gradient describes how the current changes in time. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricCurrentGradient : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricCurrentGradientUnit? _unit; - - static ElectricCurrentGradient() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); - BaseUnit = ElectricCurrentGradientUnit.AmperePerSecond; - MaxValue = new ElectricCurrentGradient(double.MaxValue, BaseUnit); - MinValue = new ElectricCurrentGradient(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCurrentGradient; - Units = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); - Zero = new ElectricCurrentGradient(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricCurrentGradient, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit AmperePerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricCurrentGradient() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricCurrentGradient(double value, ElectricCurrentGradientUnit unit) - { - if (unit == ElectricCurrentGradientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. - /// - public static ElectricCurrentGradientUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricCurrentGradient - /// - public static ElectricCurrentGradient MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCurrentGradient - /// - public static ElectricCurrentGradient MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricCurrentGradient quantity. - /// - public static ElectricCurrentGradientUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. - /// - public static ElectricCurrentGradient Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricCurrentGradient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerMicrosecond => As(ElectricCurrentGradientUnit.AmperePerMicrosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerMillisecond => As(ElectricCurrentGradientUnit.AmperePerMillisecond); - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerNanosecond => As(ElectricCurrentGradientUnit.AmperePerNanosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricCurrentGradientUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentGradient FromAmperesPerMicrosecond(double amperespermicrosecond) - { - double value = (double) amperespermicrosecond; - return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMicrosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentGradient FromAmperesPerMillisecond(double amperespermillisecond) - { - double value = (double) amperespermillisecond; - return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMillisecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentGradient FromAmperesPerNanosecond(double amperespernanosecond) - { - double value = (double) amperespernanosecond; - return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerNanosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricCurrentGradient FromAmperesPerSecond(double amperespersecond) - { - double value = (double) amperespersecond; - return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricCurrentGradient unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricCurrentGradient From(double value, ElectricCurrentGradientUnit fromUnit) - { - return new ElectricCurrentGradient((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricCurrentGradient Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCurrentGradient Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricCurrentGradient result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricCurrentGradientUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricCurrentGradientUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCurrentGradient objElectricCurrentGradient)) throw new ArgumentException("Expected type ElectricCurrentGradient.", nameof(obj)); - - return CompareTo(objElectricCurrentGradient); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricCurrentGradient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCurrentGradient objElectricCurrentGradient)) - return false; - - return Equals(objElectricCurrentGradient); - } - - public bool Equals(ElectricCurrentGradient other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricCurrentGradient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentGradient. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricCurrentGradientUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentGradientUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation . - /// - /// A ElectricCurrentGradient with the specified unit. - public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricCurrentGradient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricCurrentGradientUnit.AmperePerMicrosecond: return _value * 1E6; - case ElectricCurrentGradientUnit.AmperePerMillisecond: return _value * 1E3; - case ElectricCurrentGradientUnit.AmperePerNanosecond: return _value * 1E9; - case ElectricCurrentGradientUnit.AmperePerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricCurrentGradientUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricCurrentGradientUnit.AmperePerMicrosecond: return baseUnitValue / 1E6; - case ElectricCurrentGradientUnit.AmperePerMillisecond: return baseUnitValue / 1E3; - case ElectricCurrentGradientUnit.AmperePerNanosecond: return baseUnitValue / 1E9; - case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.g.cs deleted file mode 100644 index dea86a3a4d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricField.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. - /// - /// - /// https://en.wikipedia.org/wiki/Electric_field - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricField : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricFieldUnit? _unit; - - static ElectricField() - { - BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); - BaseUnit = ElectricFieldUnit.VoltPerMeter; - MaxValue = new ElectricField(double.MaxValue, BaseUnit); - MinValue = new ElectricField(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricField; - Units = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); - Zero = new ElectricField(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricField, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricField() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricField(double value, ElectricFieldUnit unit) - { - if (unit == ElectricFieldUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. - /// - public static ElectricFieldUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricField - /// - public static ElectricField MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricField - /// - public static ElectricField MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricField quantity. - /// - public static ElectricFieldUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. - /// - public static ElectricField Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricField.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricField.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(ElectricFieldUnit.VoltPerMeter, new CultureInfo("en-US"), false, true, new string[]{"V/m"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricFieldUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricField FromVoltsPerMeter(double voltspermeter) - { - double value = (double) voltspermeter; - return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricField unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricField From(double value, ElectricFieldUnit fromUnit) - { - return new ElectricField((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricField Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricField Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricField result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricField result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricFieldUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricFieldUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricFieldUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricField objElectricField)) throw new ArgumentException("Expected type ElectricField.", nameof(obj)); - - return CompareTo(objElectricField); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricField other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricField objElectricField)) - return false; - - return Equals(objElectricField); - } - - public bool Equals(ElectricField other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricField within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricField other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricField. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricFieldUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricFieldUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricField to another ElectricField with the unit representation . - /// - /// A ElectricField with the specified unit. - public ElectricField ToUnit(ElectricFieldUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricField(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricFieldUnit.VoltPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricFieldUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricFieldUnit.VoltPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.g.cs deleted file mode 100644 index 8a27b5f62f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricInductance.g.cs +++ /dev/null @@ -1,653 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Inductance is a property of an electrical conductor which opposes a change in current. - /// - /// - /// https://en.wikipedia.org/wiki/Inductance - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricInductance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricInductanceUnit? _unit; - - static ElectricInductance() - { - BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); - BaseUnit = ElectricInductanceUnit.Henry; - MaxValue = new ElectricInductance(double.MaxValue, BaseUnit); - MinValue = new ElectricInductance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricInductance; - Units = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); - Zero = new ElectricInductance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricInductance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Henry. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricInductance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricInductance(double value, ElectricInductanceUnit unit) - { - if (unit == ElectricInductanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. - /// - public static ElectricInductanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricInductance - /// - public static ElectricInductance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricInductance - /// - public static ElectricInductance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricInductance quantity. - /// - public static ElectricInductanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Henry. - /// - public static ElectricInductance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricInductance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Henries => As(ElectricInductanceUnit.Henry); - - /// - /// Gets a value of this quantity converted into - /// - public double Microhenries => As(ElectricInductanceUnit.Microhenry); - - /// - /// Gets a value of this quantity converted into - /// - public double Millihenries => As(ElectricInductanceUnit.Millihenry); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricInductanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromHenries(double henries) - { - double value = (double) henries; - return new ElectricInductance(value, ElectricInductanceUnit.Henry); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromMicrohenries(double microhenries) - { - double value = (double) microhenries; - return new ElectricInductance(value, ElectricInductanceUnit.Microhenry); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromMillihenries(double millihenries) - { - double value = (double) millihenries; - return new ElectricInductance(value, ElectricInductanceUnit.Millihenry); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricInductance FromNanohenries(double nanohenries) - { - double value = (double) nanohenries; - return new ElectricInductance(value, ElectricInductanceUnit.Nanohenry); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricInductance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricInductance From(double value, ElectricInductanceUnit fromUnit) - { - return new ElectricInductance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricInductance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricInductance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricInductance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricInductance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricInductanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricInductanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricInductance objElectricInductance)) throw new ArgumentException("Expected type ElectricInductance.", nameof(obj)); - - return CompareTo(objElectricInductance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricInductance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricInductance objElectricInductance)) - return false; - - return Equals(objElectricInductance); - } - - public bool Equals(ElectricInductance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricInductance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricInductance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricInductance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricInductanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricInductanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricInductance to another ElectricInductance with the unit representation . - /// - /// A ElectricInductance with the specified unit. - public ElectricInductance ToUnit(ElectricInductanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricInductance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricInductanceUnit.Henry: return _value; - case ElectricInductanceUnit.Microhenry: return (_value) * 1e-6d; - case ElectricInductanceUnit.Millihenry: return (_value) * 1e-3d; - case ElectricInductanceUnit.Nanohenry: return (_value) * 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricInductanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricInductanceUnit.Henry: return baseUnitValue; - case ElectricInductanceUnit.Microhenry: return (baseUnitValue) / 1e-6d; - case ElectricInductanceUnit.Millihenry: return (baseUnitValue) / 1e-3d; - case ElectricInductanceUnit.Nanohenry: return (baseUnitValue) / 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.g.cs deleted file mode 100644 index 3fd951d6ed..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotential.g.cs +++ /dev/null @@ -1,674 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotential : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialUnit? _unit; - - static ElectricPotential() - { - BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); - BaseUnit = ElectricPotentialUnit.Volt; - MaxValue = new ElectricPotential(double.MaxValue, BaseUnit); - MinValue = new ElectricPotential(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotential; - Units = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); - Zero = new ElectricPotential(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricPotential, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Volt. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricPotential() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricPotential(double value, ElectricPotentialUnit unit) - { - if (unit == ElectricPotentialUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. - /// - public static ElectricPotentialUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricPotential - /// - public static ElectricPotential MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotential - /// - public static ElectricPotential MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricPotential quantity. - /// - public static ElectricPotentialUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Volt. - /// - public static ElectricPotential Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricPotential.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Megavolts => As(ElectricPotentialUnit.Megavolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Microvolts => As(ElectricPotentialUnit.Microvolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Millivolts => As(ElectricPotentialUnit.Millivolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Volts => As(ElectricPotentialUnit.Volt); - - #endregion - - #region Static Methods - - 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[]{"В"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricPotentialUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromKilovolts(double kilovolts) - { - double value = (double) kilovolts; - return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMegavolts(double megavolts) - { - double value = (double) megavolts; - return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMicrovolts(double microvolts) - { - double value = (double) microvolts; - return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromMillivolts(double millivolts) - { - double value = (double) millivolts; - return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotential FromVolts(double volts) - { - double value = (double) volts; - return new ElectricPotential(value, ElectricPotentialUnit.Volt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotential unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotential From(double value, ElectricPotentialUnit fromUnit) - { - return new ElectricPotential((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotential Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotential Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotential result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricPotential result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricPotentialUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricPotential objElectricPotential)) throw new ArgumentException("Expected type ElectricPotential.", nameof(obj)); - - return CompareTo(objElectricPotential); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricPotential other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotential objElectricPotential)) - return false; - - return Equals(objElectricPotential); - } - - public bool Equals(ElectricPotential other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotential within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotential other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotential. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricPotentialUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotential to another ElectricPotential with the unit representation . - /// - /// A ElectricPotential with the specified unit. - public ElectricPotential ToUnit(ElectricPotentialUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotential(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialUnit.Kilovolt: return (_value) * 1e3d; - case ElectricPotentialUnit.Megavolt: return (_value) * 1e6d; - case ElectricPotentialUnit.Microvolt: return (_value) * 1e-6d; - case ElectricPotentialUnit.Millivolt: return (_value) * 1e-3d; - case ElectricPotentialUnit.Volt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialUnit.Kilovolt: return (baseUnitValue) / 1e3d; - case ElectricPotentialUnit.Megavolt: return (baseUnitValue) / 1e6d; - case ElectricPotentialUnit.Microvolt: return (baseUnitValue) / 1e-6d; - case ElectricPotentialUnit.Millivolt: return (baseUnitValue) / 1e-3d; - case ElectricPotentialUnit.Volt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.g.cs deleted file mode 100644 index 6877acfdb7..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ /dev/null @@ -1,669 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Electric Potential of a system known to use Alternating Current. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotentialAc : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialAcUnit? _unit; - - static ElectricPotentialAc() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = ElectricPotentialAcUnit.VoltAc; - MaxValue = new ElectricPotentialAc(double.MaxValue, BaseUnit); - MinValue = new ElectricPotentialAc(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotentialAc; - Units = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); - Zero = new ElectricPotentialAc(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricPotentialAc, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltAc. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricPotentialAc() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricPotentialAc(double value, ElectricPotentialAcUnit unit) - { - if (unit == ElectricPotentialAcUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. - /// - public static ElectricPotentialAcUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricPotentialAc - /// - public static ElectricPotentialAc MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotentialAc - /// - public static ElectricPotentialAc MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricPotentialAc quantity. - /// - public static ElectricPotentialAcUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. - /// - public static ElectricPotentialAc Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricPotentialAc.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); - - /// - /// Gets a value of this quantity converted into - /// - public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricPotentialAcUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromKilovoltsAc(double kilovoltsac) - { - double value = (double) kilovoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMegavoltsAc(double megavoltsac) - { - double value = (double) megavoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMicrovoltsAc(double microvoltsac) - { - double value = (double) microvoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromMillivoltsAc(double millivoltsac) - { - double value = (double) millivoltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialAc FromVoltsAc(double voltsac) - { - double value = (double) voltsac; - return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialAc unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fromUnit) - { - return new ElectricPotentialAc((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialAc Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialAc Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricPotentialAc result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialAcUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricPotentialAcUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricPotentialAc objElectricPotentialAc)) throw new ArgumentException("Expected type ElectricPotentialAc.", nameof(obj)); - - return CompareTo(objElectricPotentialAc); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricPotentialAc other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotentialAc objElectricPotentialAc)) - return false; - - return Equals(objElectricPotentialAc); - } - - public bool Equals(ElectricPotentialAc other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotentialAc within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialAc. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricPotentialAcUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialAcUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation . - /// - /// A ElectricPotentialAc with the specified unit. - public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialAc(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (_value) * 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (_value) * 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (_value) * 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (_value) * 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialAcUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialAcUnit.KilovoltAc: return (baseUnitValue) / 1e3d; - case ElectricPotentialAcUnit.MegavoltAc: return (baseUnitValue) / 1e6d; - case ElectricPotentialAcUnit.MicrovoltAc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialAcUnit.MillivoltAc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialAcUnit.VoltAc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs deleted file mode 100644 index 609e52bbd3..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ /dev/null @@ -1,954 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotentialChangeRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialChangeRateUnit? _unit; - - static ElectricPotentialChangeRate() - { - BaseDimensions = new BaseDimensions(2, 1, -4, -1, 0, 0, 0); - BaseUnit = ElectricPotentialChangeRateUnit.VoltPerSecond; - MaxValue = new ElectricPotentialChangeRate(double.MaxValue, BaseUnit); - MinValue = new ElectricPotentialChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotentialChangeRate; - Units = Enum.GetValues(typeof(ElectricPotentialChangeRateUnit)).Cast().Except(new ElectricPotentialChangeRateUnit[]{ ElectricPotentialChangeRateUnit.Undefined }).ToArray(); - Zero = new ElectricPotentialChangeRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricPotentialChangeRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricPotentialChangeRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricPotentialChangeRate(double value, ElectricPotentialChangeRateUnit unit) - { - if (unit == ElectricPotentialChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricPotentialChangeRate, which is VoltPerSecond. All conversions go via this value. - /// - public static ElectricPotentialChangeRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricPotentialChangeRate - /// - public static ElectricPotentialChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotentialChangeRate - /// - public static ElectricPotentialChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricPotentialChangeRate quantity. - /// - public static ElectricPotentialChangeRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerSecond. - /// - public static ElectricPotentialChangeRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricPotentialChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialChangeRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltsPerHours => As(ElectricPotentialChangeRateUnit.KilovoltPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.KilovoltPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.KilovoltPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltsPerHours => As(ElectricPotentialChangeRateUnit.MegavoltPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MegavoltPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MegavoltPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrovoltsPerHours => As(ElectricPotentialChangeRateUnit.MicrovoltPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillivoltsPerHours => As(ElectricPotentialChangeRateUnit.MillivoltPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MillivoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillivoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MillivoltPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MillivoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MillivoltPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsPerHours => As(ElectricPotentialChangeRateUnit.VoltPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsPerMinutes => As(ElectricPotentialChangeRateUnit.VoltPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsPerSeconds => As(ElectricPotentialChangeRateUnit.VoltPerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromKilovoltsPerHours(double kilovoltsperhours) - { - double value = (double) kilovoltsperhours; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromKilovoltsPerMicroseconds(double kilovoltspermicroseconds) - { - double value = (double) kilovoltspermicroseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromKilovoltsPerMinutes(double kilovoltsperminutes) - { - double value = (double) kilovoltsperminutes; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromKilovoltsPerSeconds(double kilovoltsperseconds) - { - double value = (double) kilovoltsperseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMegavoltsPerHours(double megavoltsperhours) - { - double value = (double) megavoltsperhours; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMegavoltsPerMicroseconds(double megavoltspermicroseconds) - { - double value = (double) megavoltspermicroseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMegavoltsPerMinutes(double megavoltsperminutes) - { - double value = (double) megavoltsperminutes; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMegavoltsPerSeconds(double megavoltsperseconds) - { - double value = (double) megavoltsperseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMicrovoltsPerHours(double microvoltsperhours) - { - double value = (double) microvoltsperhours; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMicrovoltsPerMicroseconds(double microvoltspermicroseconds) - { - double value = (double) microvoltspermicroseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMicrovoltsPerMinutes(double microvoltsperminutes) - { - double value = (double) microvoltsperminutes; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMicrovoltsPerSeconds(double microvoltsperseconds) - { - double value = (double) microvoltsperseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMillivoltsPerHours(double millivoltsperhours) - { - double value = (double) millivoltsperhours; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMillivoltsPerMicroseconds(double millivoltspermicroseconds) - { - double value = (double) millivoltspermicroseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMillivoltsPerMinutes(double millivoltsperminutes) - { - double value = (double) millivoltsperminutes; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromMillivoltsPerSeconds(double millivoltsperseconds) - { - double value = (double) millivoltsperseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromVoltsPerHours(double voltsperhours) - { - double value = (double) voltsperhours; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromVoltsPerMicroseconds(double voltspermicroseconds) - { - double value = (double) voltspermicroseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMicrosecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromVoltsPerMinutes(double voltsperminutes) - { - double value = (double) voltsperminutes; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialChangeRate FromVoltsPerSeconds(double voltsperseconds) - { - double value = (double) voltsperseconds; - return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialChangeRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialChangeRate From(double value, ElectricPotentialChangeRateUnit fromUnit) - { - return new ElectricPotentialChangeRate((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialChangeRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricPotentialChangeRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricPotentialChangeRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricPotentialChangeRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricPotentialChangeRate objElectricPotentialChangeRate)) throw new ArgumentException("Expected type ElectricPotentialChangeRate.", nameof(obj)); - - return CompareTo(objElectricPotentialChangeRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricPotentialChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotentialChangeRate objElectricPotentialChangeRate)) - return false; - - return Equals(objElectricPotentialChangeRate); - } - - public bool Equals(ElectricPotentialChangeRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotentialChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricPotentialChangeRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialChangeRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialChangeRate to another ElectricPotentialChangeRate with the unit representation . - /// - /// A ElectricPotentialChangeRate with the specified unit. - public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialChangeRateUnit.KilovoltPerHour: return (_value / 3600) * 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond: return (_value * 1E6) * 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMinute: return (_value / 60) * 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerSecond: return (_value) * 1e3d; - case ElectricPotentialChangeRateUnit.MegavoltPerHour: return (_value / 3600) * 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond: return (_value * 1E6) * 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMinute: return (_value / 60) * 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerSecond: return (_value) * 1e6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerHour: return (_value / 3600) * 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond: return (_value * 1E6) * 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMinute: return (_value / 60) * 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerSecond: return (_value) * 1e-6d; - case ElectricPotentialChangeRateUnit.MillivoltPerHour: return (_value / 3600) * 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond: return (_value * 1E6) * 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMinute: return (_value / 60) * 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerSecond: return (_value) * 1e-3d; - case ElectricPotentialChangeRateUnit.VoltPerHour: return _value / 3600; - case ElectricPotentialChangeRateUnit.VoltPerMicrosecond: return _value * 1E6; - case ElectricPotentialChangeRateUnit.VoltPerMinute: return _value / 60; - case ElectricPotentialChangeRateUnit.VoltPerSecond: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialChangeRateUnit.KilovoltPerHour: return (baseUnitValue * 3600) / 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond: return (baseUnitValue / 1E6) / 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerMinute: return (baseUnitValue * 60) / 1e3d; - case ElectricPotentialChangeRateUnit.KilovoltPerSecond: return (baseUnitValue) / 1e3d; - case ElectricPotentialChangeRateUnit.MegavoltPerHour: return (baseUnitValue * 3600) / 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond: return (baseUnitValue / 1E6) / 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerMinute: return (baseUnitValue * 60) / 1e6d; - case ElectricPotentialChangeRateUnit.MegavoltPerSecond: return (baseUnitValue) / 1e6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerHour: return (baseUnitValue * 3600) / 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond: return (baseUnitValue / 1E6) / 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerMinute: return (baseUnitValue * 60) / 1e-6d; - case ElectricPotentialChangeRateUnit.MicrovoltPerSecond: return (baseUnitValue) / 1e-6d; - case ElectricPotentialChangeRateUnit.MillivoltPerHour: return (baseUnitValue * 3600) / 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond: return (baseUnitValue / 1E6) / 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerMinute: return (baseUnitValue * 60) / 1e-3d; - case ElectricPotentialChangeRateUnit.MillivoltPerSecond: return (baseUnitValue) / 1e-3d; - case ElectricPotentialChangeRateUnit.VoltPerHour: return baseUnitValue * 3600; - case ElectricPotentialChangeRateUnit.VoltPerMicrosecond: return baseUnitValue / 1E6; - case ElectricPotentialChangeRateUnit.VoltPerMinute: return baseUnitValue * 60; - case ElectricPotentialChangeRateUnit.VoltPerSecond: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.g.cs deleted file mode 100644 index 6526515c3f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ /dev/null @@ -1,669 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Electric Potential of a system known to use Direct Current. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricPotentialDc : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricPotentialDcUnit? _unit; - - static ElectricPotentialDc() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = ElectricPotentialDcUnit.VoltDc; - MaxValue = new ElectricPotentialDc(double.MaxValue, BaseUnit); - MinValue = new ElectricPotentialDc(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotentialDc; - Units = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); - Zero = new ElectricPotentialDc(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricPotentialDc, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltDc. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricPotentialDc() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricPotentialDc(double value, ElectricPotentialDcUnit unit) - { - if (unit == ElectricPotentialDcUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. - /// - public static ElectricPotentialDcUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricPotentialDc - /// - public static ElectricPotentialDc MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotentialDc - /// - public static ElectricPotentialDc MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricPotentialDc quantity. - /// - public static ElectricPotentialDcUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. - /// - public static ElectricPotentialDc Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricPotentialDc.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); - - /// - /// Gets a value of this quantity converted into - /// - public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricPotentialDcUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromKilovoltsDc(double kilovoltsdc) - { - double value = (double) kilovoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMegavoltsDc(double megavoltsdc) - { - double value = (double) megavoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMicrovoltsDc(double microvoltsdc) - { - double value = (double) microvoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromMillivoltsDc(double millivoltsdc) - { - double value = (double) millivoltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricPotentialDc FromVoltsDc(double voltsdc) - { - double value = (double) voltsdc; - return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricPotentialDc unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fromUnit) - { - return new ElectricPotentialDc((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricPotentialDc Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialDc Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricPotentialDc result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricPotentialDcUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricPotentialDcUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricPotentialDc objElectricPotentialDc)) throw new ArgumentException("Expected type ElectricPotentialDc.", nameof(obj)); - - return CompareTo(objElectricPotentialDc); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricPotentialDc other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotentialDc objElectricPotentialDc)) - return false; - - return Equals(objElectricPotentialDc); - } - - public bool Equals(ElectricPotentialDc other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricPotentialDc within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricPotentialDc other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialDc. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricPotentialDcUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialDcUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation . - /// - /// A ElectricPotentialDc with the specified unit. - public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricPotentialDc(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (_value) * 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (_value) * 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (_value) * 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (_value) * 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricPotentialDcUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricPotentialDcUnit.KilovoltDc: return (baseUnitValue) / 1e3d; - case ElectricPotentialDcUnit.MegavoltDc: return (baseUnitValue) / 1e6d; - case ElectricPotentialDcUnit.MicrovoltDc: return (baseUnitValue) / 1e-6d; - case ElectricPotentialDcUnit.MillivoltDc: return (baseUnitValue) / 1e-3d; - case ElectricPotentialDcUnit.VoltDc: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.g.cs deleted file mode 100644 index 001c5e547d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistance.g.cs +++ /dev/null @@ -1,688 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricResistance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricResistanceUnit? _unit; - - static ElectricResistance() - { - BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); - BaseUnit = ElectricResistanceUnit.Ohm; - MaxValue = new ElectricResistance(double.MaxValue, BaseUnit); - MinValue = new ElectricResistance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricResistance; - Units = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); - Zero = new ElectricResistance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricResistance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Ohm. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricResistance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricResistance(double value, ElectricResistanceUnit unit) - { - if (unit == ElectricResistanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. - /// - public static ElectricResistanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricResistance - /// - public static ElectricResistance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricResistance - /// - public static ElectricResistance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricResistance quantity. - /// - public static ElectricResistanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. - /// - public static ElectricResistance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricResistance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); - - /// - /// Gets a value of this quantity converted into - /// - public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); - - /// - /// Gets a value of this quantity converted into - /// - public double Megaohms => As(ElectricResistanceUnit.Megaohm); - - /// - /// Gets a value of this quantity converted into - /// - public double Microohms => As(ElectricResistanceUnit.Microohm); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliohms => As(ElectricResistanceUnit.Milliohm); - - /// - /// Gets a value of this quantity converted into - /// - public double Ohms => As(ElectricResistanceUnit.Ohm); - - #endregion - - #region Static Methods - - 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[]{"Ω"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricResistanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromGigaohms(double gigaohms) - { - double value = (double) gigaohms; - return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromKiloohms(double kiloohms) - { - double value = (double) kiloohms; - return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMegaohms(double megaohms) - { - double value = (double) megaohms; - return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMicroohms(double microohms) - { - double value = (double) microohms; - return new ElectricResistance(value, ElectricResistanceUnit.Microohm); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromMilliohms(double milliohms) - { - double value = (double) milliohms; - return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistance FromOhms(double ohms) - { - double value = (double) ohms; - return new ElectricResistance(value, ElectricResistanceUnit.Ohm); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricResistance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricResistance From(double value, ElectricResistanceUnit fromUnit) - { - return new ElectricResistance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricResistance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricResistance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricResistance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricResistance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricResistanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricResistance objElectricResistance)) throw new ArgumentException("Expected type ElectricResistance.", nameof(obj)); - - return CompareTo(objElectricResistance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricResistance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricResistance objElectricResistance)) - return false; - - return Equals(objElectricResistance); - } - - public bool Equals(ElectricResistance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricResistance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricResistance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricResistanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricResistance to another ElectricResistance with the unit representation . - /// - /// A ElectricResistance with the specified unit. - public ElectricResistance ToUnit(ElectricResistanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricResistance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricResistanceUnit.Gigaohm: return (_value) * 1e9d; - case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d; - case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d; - case ElectricResistanceUnit.Microohm: return (_value) * 1e-6d; - case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d; - case ElectricResistanceUnit.Ohm: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricResistanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricResistanceUnit.Gigaohm: return (baseUnitValue) / 1e9d; - case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d; - case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d; - case ElectricResistanceUnit.Microohm: return (baseUnitValue) / 1e-6d; - case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d; - case ElectricResistanceUnit.Ohm: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.g.cs deleted file mode 100644 index 4c6c79edd1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ /dev/null @@ -1,843 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current. - /// - /// - /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricResistivity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricResistivityUnit? _unit; - - static ElectricResistivity() - { - BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); - BaseUnit = ElectricResistivityUnit.OhmMeter; - MaxValue = new ElectricResistivity(double.MaxValue, BaseUnit); - MinValue = new ElectricResistivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricResistivity; - Units = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); - Zero = new ElectricResistivity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricResistivity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit OhmMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricResistivity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricResistivity(double value, ElectricResistivityUnit unit) - { - if (unit == ElectricResistivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. - /// - public static ElectricResistivityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricResistivity - /// - public static ElectricResistivity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricResistivity - /// - public static ElectricResistivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricResistivity quantity. - /// - public static ElectricResistivityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. - /// - public static ElectricResistivity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricResistivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KiloohmsCentimeter => As(ElectricResistivityUnit.KiloohmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KiloohmMeters => As(ElectricResistivityUnit.KiloohmMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegaohmsCentimeter => As(ElectricResistivityUnit.MegaohmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegaohmMeters => As(ElectricResistivityUnit.MegaohmMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicroohmsCentimeter => As(ElectricResistivityUnit.MicroohmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliohmsCentimeter => As(ElectricResistivityUnit.MilliohmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanoohmsCentimeter => As(ElectricResistivityUnit.NanoohmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double OhmsCentimeter => As(ElectricResistivityUnit.OhmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicoohmsCentimeter => As(ElectricResistivityUnit.PicoohmCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicoohmMeters => As(ElectricResistivityUnit.PicoohmMeter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricResistivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromKiloohmsCentimeter(double kiloohmscentimeter) - { - double value = (double) kiloohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromKiloohmMeters(double kiloohmmeters) - { - double value = (double) kiloohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMegaohmsCentimeter(double megaohmscentimeter) - { - double value = (double) megaohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMegaohmMeters(double megaohmmeters) - { - double value = (double) megaohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMicroohmsCentimeter(double microohmscentimeter) - { - double value = (double) microohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMicroohmMeters(double microohmmeters) - { - double value = (double) microohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMilliohmsCentimeter(double milliohmscentimeter) - { - double value = (double) milliohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromMilliohmMeters(double milliohmmeters) - { - double value = (double) milliohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromNanoohmsCentimeter(double nanoohmscentimeter) - { - double value = (double) nanoohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromNanoohmMeters(double nanoohmmeters) - { - double value = (double) nanoohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromOhmsCentimeter(double ohmscentimeter) - { - double value = (double) ohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.OhmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromOhmMeters(double ohmmeters) - { - double value = (double) ohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromPicoohmsCentimeter(double picoohmscentimeter) - { - double value = (double) picoohmscentimeter; - return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricResistivity FromPicoohmMeters(double picoohmmeters) - { - double value = (double) picoohmmeters; - return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricResistivity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricResistivity From(double value, ElectricResistivityUnit fromUnit) - { - return new ElectricResistivity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricResistivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricResistivity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricResistivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricResistivity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricResistivityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricResistivityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricResistivity objElectricResistivity)) throw new ArgumentException("Expected type ElectricResistivity.", nameof(obj)); - - return CompareTo(objElectricResistivity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricResistivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricResistivity objElectricResistivity)) - return false; - - return Equals(objElectricResistivity); - } - - public bool Equals(ElectricResistivity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricResistivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ElectricResistivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricResistivityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistivityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . - /// - /// A ElectricResistivity with the specified unit. - public ElectricResistivity ToUnit(ElectricResistivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricResistivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricResistivityUnit.KiloohmCentimeter: return (_value / 100) * 1e3d; - case ElectricResistivityUnit.KiloohmMeter: return (_value) * 1e3d; - case ElectricResistivityUnit.MegaohmCentimeter: return (_value / 100) * 1e6d; - case ElectricResistivityUnit.MegaohmMeter: return (_value) * 1e6d; - case ElectricResistivityUnit.MicroohmCentimeter: return (_value / 100) * 1e-6d; - case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; - case ElectricResistivityUnit.MilliohmCentimeter: return (_value / 100) * 1e-3d; - case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; - case ElectricResistivityUnit.NanoohmCentimeter: return (_value / 100) * 1e-9d; - case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; - case ElectricResistivityUnit.OhmCentimeter: return _value / 100; - case ElectricResistivityUnit.OhmMeter: return _value; - case ElectricResistivityUnit.PicoohmCentimeter: return (_value / 100) * 1e-12d; - case ElectricResistivityUnit.PicoohmMeter: return (_value) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricResistivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricResistivityUnit.KiloohmCentimeter: return (baseUnitValue * 100) / 1e3d; - case ElectricResistivityUnit.KiloohmMeter: return (baseUnitValue) / 1e3d; - case ElectricResistivityUnit.MegaohmCentimeter: return (baseUnitValue * 100) / 1e6d; - case ElectricResistivityUnit.MegaohmMeter: return (baseUnitValue) / 1e6d; - case ElectricResistivityUnit.MicroohmCentimeter: return (baseUnitValue * 100) / 1e-6d; - case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; - case ElectricResistivityUnit.MilliohmCentimeter: return (baseUnitValue * 100) / 1e-3d; - case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; - case ElectricResistivityUnit.NanoohmCentimeter: return (baseUnitValue * 100) / 1e-9d; - case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; - case ElectricResistivityUnit.OhmCentimeter: return baseUnitValue * 100; - case ElectricResistivityUnit.OhmMeter: return baseUnitValue; - case ElectricResistivityUnit.PicoohmCentimeter: return (baseUnitValue * 100) / 1e-12d; - case ElectricResistivityUnit.PicoohmMeter: return (baseUnitValue) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs deleted file mode 100644 index 01af6bb6c2..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ /dev/null @@ -1,634 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area. - /// - /// - /// https://en.wikipedia.org/wiki/Charge_density - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ElectricSurfaceChargeDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ElectricSurfaceChargeDensityUnit? _unit; - - static ElectricSurfaceChargeDensity() - { - BaseDimensions = new BaseDimensions(-2, 0, 1, 1, 0, 0, 0); - BaseUnit = ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter; - MaxValue = new ElectricSurfaceChargeDensity(double.MaxValue, BaseUnit); - MinValue = new ElectricSurfaceChargeDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricSurfaceChargeDensity; - Units = Enum.GetValues(typeof(ElectricSurfaceChargeDensityUnit)).Cast().Except(new ElectricSurfaceChargeDensityUnit[]{ ElectricSurfaceChargeDensityUnit.Undefined }).ToArray(); - Zero = new ElectricSurfaceChargeDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ElectricSurfaceChargeDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CoulombPerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ElectricSurfaceChargeDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ElectricSurfaceChargeDensity(double value, ElectricSurfaceChargeDensityUnit unit) - { - if (unit == ElectricSurfaceChargeDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ElectricSurfaceChargeDensity, which is CoulombPerSquareMeter. All conversions go via this value. - /// - public static ElectricSurfaceChargeDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ElectricSurfaceChargeDensity - /// - public static ElectricSurfaceChargeDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricSurfaceChargeDensity - /// - public static ElectricSurfaceChargeDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ElectricSurfaceChargeDensity quantity. - /// - public static ElectricSurfaceChargeDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerSquareMeter. - /// - public static ElectricSurfaceChargeDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ElectricSurfaceChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ElectricSurfaceChargeDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ElectricSurfaceChargeDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CoulombsPerSquareCentimeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CoulombsPerSquareInch => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double CoulombsPerSquareMeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(double coulombspersquarecentimeter) - { - double value = (double) coulombspersquarecentimeter; - return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(double coulombspersquareinch) - { - double value = (double) coulombspersquareinch; - return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(double coulombspersquaremeter) - { - double value = (double) coulombspersquaremeter; - return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ElectricSurfaceChargeDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ElectricSurfaceChargeDensity From(double value, ElectricSurfaceChargeDensityUnit fromUnit) - { - return new ElectricSurfaceChargeDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ElectricSurfaceChargeDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricSurfaceChargeDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ElectricSurfaceChargeDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ElectricSurfaceChargeDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ElectricSurfaceChargeDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ElectricSurfaceChargeDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ElectricSurfaceChargeDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ElectricSurfaceChargeDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricSurfaceChargeDensity objElectricSurfaceChargeDensity)) throw new ArgumentException("Expected type ElectricSurfaceChargeDensity.", nameof(obj)); - - return CompareTo(objElectricSurfaceChargeDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ElectricSurfaceChargeDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricSurfaceChargeDensity objElectricSurfaceChargeDensity)) - return false; - - return Equals(objElectricSurfaceChargeDensity); - } - - public bool Equals(ElectricSurfaceChargeDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ElectricSurfaceChargeDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricSurfaceChargeDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ElectricSurfaceChargeDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricSurfaceChargeDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ElectricSurfaceChargeDensity to another ElectricSurfaceChargeDensity with the unit representation . - /// - /// A ElectricSurfaceChargeDensity with the specified unit. - public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ElectricSurfaceChargeDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter: return _value * 1.0e4; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch: return _value * 1.5500031000062000e3; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ElectricSurfaceChargeDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter: return baseUnitValue / 1.0e4; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch: return baseUnitValue / 1.5500031000062000e3; - case ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.g.cs deleted file mode 100644 index c39a0f6701..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Energy.g.cs +++ /dev/null @@ -1,1317 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Energy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly EnergyUnit? _unit; - - static Energy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = EnergyUnit.Joule; - MaxValue = new Energy(double.MaxValue, BaseUnit); - MinValue = new Energy(double.MinValue, BaseUnit); - QuantityType = QuantityType.Energy; - Units = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); - Zero = new Energy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Energy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Joule. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Energy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Energy(double value, EnergyUnit unit) - { - if (unit == EnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Energy, which is Joule. All conversions go via this value. - /// - public static EnergyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Energy - /// - public static Energy MaxValue { get; } - - /// - /// Represents the smallest possible value of Energy - /// - public static Energy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Energy quantity. - /// - public static EnergyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Joule. - /// - public static Energy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Energy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Energy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); - - /// - /// Gets a value of this quantity converted into - /// - public double Calories => As(EnergyUnit.Calorie); - - /// - /// Gets a value of this quantity converted into - /// - public double DecathermsEc => As(EnergyUnit.DecathermEc); - - /// - /// Gets a value of this quantity converted into - /// - public double DecathermsImperial => As(EnergyUnit.DecathermImperial); - - /// - /// Gets a value of this quantity converted into - /// - public double DecathermsUs => As(EnergyUnit.DecathermUs); - - /// - /// Gets a value of this quantity converted into - /// - public double ElectronVolts => As(EnergyUnit.ElectronVolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Ergs => As(EnergyUnit.Erg); - - /// - /// Gets a value of this quantity converted into - /// - public double FootPounds => As(EnergyUnit.FootPound); - - /// - /// Gets a value of this quantity converted into - /// - public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); - - /// - /// Gets a value of this quantity converted into - /// - public double GigaelectronVolts => As(EnergyUnit.GigaelectronVolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigajoules => As(EnergyUnit.Gigajoule); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattDays => As(EnergyUnit.GigawattDay); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattHours => As(EnergyUnit.GigawattHour); - - /// - /// Gets a value of this quantity converted into - /// - public double HorsepowerHours => As(EnergyUnit.HorsepowerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Joules => As(EnergyUnit.Joule); - - /// - /// Gets a value of this quantity converted into - /// - public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilocalories => As(EnergyUnit.Kilocalorie); - - /// - /// Gets a value of this quantity converted into - /// - public double KiloelectronVolts => As(EnergyUnit.KiloelectronVolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilojoules => As(EnergyUnit.Kilojoule); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattDays => As(EnergyUnit.KilowattDay); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattHours => As(EnergyUnit.KilowattHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); - - /// - /// Gets a value of this quantity converted into - /// - public double Megacalories => As(EnergyUnit.Megacalorie); - - /// - /// Gets a value of this quantity converted into - /// - public double MegaelectronVolts => As(EnergyUnit.MegaelectronVolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Megajoules => As(EnergyUnit.Megajoule); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattDays => As(EnergyUnit.MegawattDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattHours => As(EnergyUnit.MegawattHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Millijoules => As(EnergyUnit.Millijoule); - - /// - /// Gets a value of this quantity converted into - /// - public double Petajoules => As(EnergyUnit.Petajoule); - - /// - /// Gets a value of this quantity converted into - /// - public double TeraelectronVolts => As(EnergyUnit.TeraelectronVolt); - - /// - /// Gets a value of this quantity converted into - /// - public double Terajoules => As(EnergyUnit.Terajoule); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattDays => As(EnergyUnit.TerawattDay); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattHours => As(EnergyUnit.TerawattHour); - - /// - /// Gets a value of this quantity converted into - /// - public double ThermsEc => As(EnergyUnit.ThermEc); - - /// - /// Gets a value of this quantity converted into - /// - public double ThermsImperial => As(EnergyUnit.ThermImperial); - - /// - /// Gets a value of this quantity converted into - /// - public double ThermsUs => As(EnergyUnit.ThermUs); - - /// - /// Gets a value of this quantity converted into - /// - public double WattDays => As(EnergyUnit.WattDay); - - /// - /// Gets a value of this quantity converted into - /// - public double WattHours => As(EnergyUnit.WattHour); - - #endregion - - #region Static Methods - - 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[]{"Вт/ч"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(EnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromBritishThermalUnits(double britishthermalunits) - { - double value = (double) britishthermalunits; - return new Energy(value, EnergyUnit.BritishThermalUnit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromCalories(double calories) - { - double value = (double) calories; - return new Energy(value, EnergyUnit.Calorie); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsEc(double decathermsec) - { - double value = (double) decathermsec; - return new Energy(value, EnergyUnit.DecathermEc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsImperial(double decathermsimperial) - { - double value = (double) decathermsimperial; - return new Energy(value, EnergyUnit.DecathermImperial); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromDecathermsUs(double decathermsus) - { - double value = (double) decathermsus; - return new Energy(value, EnergyUnit.DecathermUs); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromElectronVolts(double electronvolts) - { - double value = (double) electronvolts; - return new Energy(value, EnergyUnit.ElectronVolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromErgs(double ergs) - { - double value = (double) ergs; - return new Energy(value, EnergyUnit.Erg); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromFootPounds(double footpounds) - { - double value = (double) footpounds; - return new Energy(value, EnergyUnit.FootPound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigabritishThermalUnits(double gigabritishthermalunits) - { - double value = (double) gigabritishthermalunits; - return new Energy(value, EnergyUnit.GigabritishThermalUnit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigaelectronVolts(double gigaelectronvolts) - { - double value = (double) gigaelectronvolts; - return new Energy(value, EnergyUnit.GigaelectronVolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigajoules(double gigajoules) - { - double value = (double) gigajoules; - return new Energy(value, EnergyUnit.Gigajoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigawattDays(double gigawattdays) - { - double value = (double) gigawattdays; - return new Energy(value, EnergyUnit.GigawattDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromGigawattHours(double gigawatthours) - { - double value = (double) gigawatthours; - return new Energy(value, EnergyUnit.GigawattHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromHorsepowerHours(double horsepowerhours) - { - double value = (double) horsepowerhours; - return new Energy(value, EnergyUnit.HorsepowerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromJoules(double joules) - { - double value = (double) joules; - return new Energy(value, EnergyUnit.Joule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilobritishThermalUnits(double kilobritishthermalunits) - { - double value = (double) kilobritishthermalunits; - return new Energy(value, EnergyUnit.KilobritishThermalUnit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilocalories(double kilocalories) - { - double value = (double) kilocalories; - return new Energy(value, EnergyUnit.Kilocalorie); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKiloelectronVolts(double kiloelectronvolts) - { - double value = (double) kiloelectronvolts; - return new Energy(value, EnergyUnit.KiloelectronVolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilojoules(double kilojoules) - { - double value = (double) kilojoules; - return new Energy(value, EnergyUnit.Kilojoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilowattDays(double kilowattdays) - { - double value = (double) kilowattdays; - return new Energy(value, EnergyUnit.KilowattDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromKilowattHours(double kilowatthours) - { - double value = (double) kilowatthours; - return new Energy(value, EnergyUnit.KilowattHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegabritishThermalUnits(double megabritishthermalunits) - { - double value = (double) megabritishthermalunits; - return new Energy(value, EnergyUnit.MegabritishThermalUnit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegacalories(double megacalories) - { - double value = (double) megacalories; - return new Energy(value, EnergyUnit.Megacalorie); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegaelectronVolts(double megaelectronvolts) - { - double value = (double) megaelectronvolts; - return new Energy(value, EnergyUnit.MegaelectronVolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegajoules(double megajoules) - { - double value = (double) megajoules; - return new Energy(value, EnergyUnit.Megajoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegawattDays(double megawattdays) - { - double value = (double) megawattdays; - return new Energy(value, EnergyUnit.MegawattDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMegawattHours(double megawatthours) - { - double value = (double) megawatthours; - return new Energy(value, EnergyUnit.MegawattHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromMillijoules(double millijoules) - { - double value = (double) millijoules; - return new Energy(value, EnergyUnit.Millijoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromPetajoules(double petajoules) - { - double value = (double) petajoules; - return new Energy(value, EnergyUnit.Petajoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromTeraelectronVolts(double teraelectronvolts) - { - double value = (double) teraelectronvolts; - return new Energy(value, EnergyUnit.TeraelectronVolt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromTerajoules(double terajoules) - { - double value = (double) terajoules; - return new Energy(value, EnergyUnit.Terajoule); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromTerawattDays(double terawattdays) - { - double value = (double) terawattdays; - return new Energy(value, EnergyUnit.TerawattDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromTerawattHours(double terawatthours) - { - double value = (double) terawatthours; - return new Energy(value, EnergyUnit.TerawattHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsEc(double thermsec) - { - double value = (double) thermsec; - return new Energy(value, EnergyUnit.ThermEc); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsImperial(double thermsimperial) - { - double value = (double) thermsimperial; - return new Energy(value, EnergyUnit.ThermImperial); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromThermsUs(double thermsus) - { - double value = (double) thermsus; - return new Energy(value, EnergyUnit.ThermUs); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromWattDays(double wattdays) - { - double value = (double) wattdays; - return new Energy(value, EnergyUnit.WattDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Energy FromWattHours(double watthours) - { - double value = (double) watthours; - return new Energy(value, EnergyUnit.WattHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Energy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Energy From(double value, EnergyUnit fromUnit) - { - return new Energy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Energy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Energy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Energy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Energy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EnergyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out EnergyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out EnergyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Energy objEnergy)) throw new ArgumentException("Expected type Energy.", nameof(obj)); - - return CompareTo(objEnergy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Energy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Energy objEnergy)) - return false; - - return Equals(objEnergy); - } - - public bool Equals(Energy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Energy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Energy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Energy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((EnergyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Energy to another Energy with the unit representation . - /// - /// A Energy with the specified unit. - public Energy ToUnit(EnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Energy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case EnergyUnit.BritishThermalUnit: return _value * 1055.05585262; - case EnergyUnit.Calorie: return _value * 4.184; - case EnergyUnit.DecathermEc: return (_value * 1.05505585262e8) * 1e1d; - case EnergyUnit.DecathermImperial: return (_value * 1.05505585257348e8) * 1e1d; - case EnergyUnit.DecathermUs: return (_value * 1.054804e8) * 1e1d; - case EnergyUnit.ElectronVolt: return _value * 1.602176565e-19; - case EnergyUnit.Erg: return _value * 1e-7; - case EnergyUnit.FootPound: return _value * 1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (_value * 1055.05585262) * 1e9d; - case EnergyUnit.GigaelectronVolt: return (_value * 1.602176565e-19) * 1e9d; - case EnergyUnit.Gigajoule: return (_value) * 1e9d; - case EnergyUnit.GigawattDay: return (_value * 24 * 3600d) * 1e9d; - case EnergyUnit.GigawattHour: return (_value * 3600d) * 1e9d; - case EnergyUnit.HorsepowerHour: return _value * 2.6845195377e6; - case EnergyUnit.Joule: return _value; - case EnergyUnit.KilobritishThermalUnit: return (_value * 1055.05585262) * 1e3d; - case EnergyUnit.Kilocalorie: return (_value * 4.184) * 1e3d; - case EnergyUnit.KiloelectronVolt: return (_value * 1.602176565e-19) * 1e3d; - case EnergyUnit.Kilojoule: return (_value) * 1e3d; - case EnergyUnit.KilowattDay: return (_value * 24 * 3600d) * 1e3d; - case EnergyUnit.KilowattHour: return (_value * 3600d) * 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (_value * 1055.05585262) * 1e6d; - case EnergyUnit.Megacalorie: return (_value * 4.184) * 1e6d; - case EnergyUnit.MegaelectronVolt: return (_value * 1.602176565e-19) * 1e6d; - case EnergyUnit.Megajoule: return (_value) * 1e6d; - case EnergyUnit.MegawattDay: return (_value * 24 * 3600d) * 1e6d; - case EnergyUnit.MegawattHour: return (_value * 3600d) * 1e6d; - case EnergyUnit.Millijoule: return (_value) * 1e-3d; - case EnergyUnit.Petajoule: return (_value) * 1e15d; - case EnergyUnit.TeraelectronVolt: return (_value * 1.602176565e-19) * 1e12d; - case EnergyUnit.Terajoule: return (_value) * 1e12d; - case EnergyUnit.TerawattDay: return (_value * 24 * 3600d) * 1e12d; - case EnergyUnit.TerawattHour: return (_value * 3600d) * 1e12d; - case EnergyUnit.ThermEc: return _value * 1.05505585262e8; - case EnergyUnit.ThermImperial: return _value * 1.05505585257348e8; - case EnergyUnit.ThermUs: return _value * 1.054804e8; - case EnergyUnit.WattDay: return _value * 24 * 3600d; - case EnergyUnit.WattHour: return _value * 3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(EnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case EnergyUnit.BritishThermalUnit: return baseUnitValue / 1055.05585262; - case EnergyUnit.Calorie: return baseUnitValue / 4.184; - case EnergyUnit.DecathermEc: return (baseUnitValue / 1.05505585262e8) / 1e1d; - case EnergyUnit.DecathermImperial: return (baseUnitValue / 1.05505585257348e8) / 1e1d; - case EnergyUnit.DecathermUs: return (baseUnitValue / 1.054804e8) / 1e1d; - case EnergyUnit.ElectronVolt: return baseUnitValue / 1.602176565e-19; - case EnergyUnit.Erg: return baseUnitValue / 1e-7; - case EnergyUnit.FootPound: return baseUnitValue / 1.355817948; - case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue / 1055.05585262) / 1e9d; - case EnergyUnit.GigaelectronVolt: return (baseUnitValue / 1.602176565e-19) / 1e9d; - case EnergyUnit.Gigajoule: return (baseUnitValue) / 1e9d; - case EnergyUnit.GigawattDay: return (baseUnitValue / (24 * 3600d)) / 1e9d; - case EnergyUnit.GigawattHour: return (baseUnitValue / 3600d) / 1e9d; - case EnergyUnit.HorsepowerHour: return baseUnitValue / 2.6845195377e6; - case EnergyUnit.Joule: return baseUnitValue; - case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue / 1055.05585262) / 1e3d; - case EnergyUnit.Kilocalorie: return (baseUnitValue / 4.184) / 1e3d; - case EnergyUnit.KiloelectronVolt: return (baseUnitValue / 1.602176565e-19) / 1e3d; - case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; - case EnergyUnit.KilowattDay: return (baseUnitValue / (24 * 3600d)) / 1e3d; - case EnergyUnit.KilowattHour: return (baseUnitValue / 3600d) / 1e3d; - case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue / 1055.05585262) / 1e6d; - case EnergyUnit.Megacalorie: return (baseUnitValue / 4.184) / 1e6d; - case EnergyUnit.MegaelectronVolt: return (baseUnitValue / 1.602176565e-19) / 1e6d; - case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; - case EnergyUnit.MegawattDay: return (baseUnitValue / (24 * 3600d)) / 1e6d; - case EnergyUnit.MegawattHour: return (baseUnitValue / 3600d) / 1e6d; - case EnergyUnit.Millijoule: return (baseUnitValue) / 1e-3d; - case EnergyUnit.Petajoule: return (baseUnitValue) / 1e15d; - case EnergyUnit.TeraelectronVolt: return (baseUnitValue / 1.602176565e-19) / 1e12d; - case EnergyUnit.Terajoule: return (baseUnitValue) / 1e12d; - case EnergyUnit.TerawattDay: return (baseUnitValue / (24 * 3600d)) / 1e12d; - case EnergyUnit.TerawattHour: return (baseUnitValue / 3600d) / 1e12d; - case EnergyUnit.ThermEc: return baseUnitValue / 1.05505585262e8; - case EnergyUnit.ThermImperial: return baseUnitValue / 1.05505585257348e8; - case EnergyUnit.ThermUs: return baseUnitValue / 1.054804e8; - case EnergyUnit.WattDay: return baseUnitValue / (24 * 3600d); - case EnergyUnit.WattHour: return baseUnitValue / 3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.g.cs deleted file mode 100644 index 838eae2e06..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Entropy.g.cs +++ /dev/null @@ -1,707 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Entropy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly EntropyUnit? _unit; - - static Entropy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); - BaseUnit = EntropyUnit.JoulePerKelvin; - MaxValue = new Entropy(double.MaxValue, BaseUnit); - MinValue = new Entropy(double.MinValue, BaseUnit); - QuantityType = QuantityType.Entropy; - Units = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); - Zero = new Entropy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Entropy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Entropy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Entropy(double value, EntropyUnit unit) - { - if (unit == EntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. - /// - public static EntropyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Entropy - /// - public static Entropy MaxValue { get; } - - /// - /// Represents the smallest possible value of Entropy - /// - public static Entropy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Entropy quantity. - /// - public static EntropyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. - /// - public static Entropy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Entropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Entropy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(EntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromCaloriesPerKelvin(double caloriesperkelvin) - { - double value = (double) caloriesperkelvin; - return new Entropy(value, EntropyUnit.CaloriePerKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromJoulesPerDegreeCelsius(double joulesperdegreecelsius) - { - double value = (double) joulesperdegreecelsius; - return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromJoulesPerKelvin(double joulesperkelvin) - { - double value = (double) joulesperkelvin; - return new Entropy(value, EntropyUnit.JoulePerKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilocaloriesPerKelvin(double kilocaloriesperkelvin) - { - double value = (double) kilocaloriesperkelvin; - return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilojoulesPerDegreeCelsius(double kilojoulesperdegreecelsius) - { - double value = (double) kilojoulesperdegreecelsius; - return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromKilojoulesPerKelvin(double kilojoulesperkelvin) - { - double value = (double) kilojoulesperkelvin; - return new Entropy(value, EntropyUnit.KilojoulePerKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Entropy FromMegajoulesPerKelvin(double megajoulesperkelvin) - { - double value = (double) megajoulesperkelvin; - return new Entropy(value, EntropyUnit.MegajoulePerKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Entropy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Entropy From(double value, EntropyUnit fromUnit) - { - return new Entropy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Entropy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Entropy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Entropy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Entropy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static EntropyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out EntropyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out EntropyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Entropy objEntropy)) throw new ArgumentException("Expected type Entropy.", nameof(obj)); - - return CompareTo(objEntropy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Entropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Entropy objEntropy)) - return false; - - return Equals(objEntropy); - } - - public bool Equals(Entropy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Entropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Entropy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Entropy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((EntropyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EntropyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Entropy to another Entropy with the unit representation . - /// - /// A Entropy with the specified unit. - public Entropy ToUnit(EntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Entropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case EntropyUnit.CaloriePerKelvin: return _value * 4.184; - case EntropyUnit.JoulePerDegreeCelsius: return _value; - case EntropyUnit.JoulePerKelvin: return _value; - case EntropyUnit.KilocaloriePerKelvin: return (_value * 4.184) * 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (_value) * 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (_value) * 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(EntropyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case EntropyUnit.CaloriePerKelvin: return baseUnitValue / 4.184; - case EntropyUnit.JoulePerDegreeCelsius: return baseUnitValue; - case EntropyUnit.JoulePerKelvin: return baseUnitValue; - case EntropyUnit.KilocaloriePerKelvin: return (baseUnitValue / 4.184) / 1e3d; - case EntropyUnit.KilojoulePerDegreeCelsius: return (baseUnitValue) / 1e3d; - case EntropyUnit.KilojoulePerKelvin: return (baseUnitValue) / 1e3d; - case EntropyUnit.MegajoulePerKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.g.cs deleted file mode 100644 index 067497d32c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Force.g.cs +++ /dev/null @@ -1,872 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Force : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForceUnit? _unit; - - static Force() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - BaseUnit = ForceUnit.Newton; - MaxValue = new Force(double.MaxValue, BaseUnit); - MinValue = new Force(double.MinValue, BaseUnit); - QuantityType = QuantityType.Force; - Units = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); - Zero = new Force(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Force, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Newton. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Force() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Force(double value, ForceUnit unit) - { - if (unit == ForceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Force, which is Newton. All conversions go via this value. - /// - public static ForceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Force - /// - public static Force MaxValue { get; } - - /// - /// Represents the smallest possible value of Force - /// - public static Force MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Force quantity. - /// - public static ForceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Newton. - /// - public static Force Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Force.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Force.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Decanewtons => As(ForceUnit.Decanewton); - - /// - /// Gets a value of this quantity converted into - /// - public double Dyne => As(ForceUnit.Dyn); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForce => As(ForceUnit.KilogramForce); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilonewtons => As(ForceUnit.Kilonewton); - - /// - /// Gets a value of this quantity converted into - /// - public double KiloPonds => As(ForceUnit.KiloPond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForce => As(ForceUnit.KilopoundForce); - - /// - /// Gets a value of this quantity converted into - /// - public double Meganewtons => As(ForceUnit.Meganewton); - - /// - /// Gets a value of this quantity converted into - /// - public double Micronewtons => As(ForceUnit.Micronewton); - - /// - /// Gets a value of this quantity converted into - /// - public double Millinewtons => As(ForceUnit.Millinewton); - - /// - /// Gets a value of this quantity converted into - /// - public double Newtons => As(ForceUnit.Newton); - - /// - /// Gets a value of this quantity converted into - /// - public double OunceForce => As(ForceUnit.OunceForce); - - /// - /// Gets a value of this quantity converted into - /// - public double Poundals => As(ForceUnit.Poundal); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForce => As(ForceUnit.PoundForce); - - /// - /// Gets a value of this quantity converted into - /// - public double ShortTonsForce => As(ForceUnit.ShortTonForce); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForce => As(ForceUnit.TonneForce); - - #endregion - - #region Static Methods - - 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[]{"тс"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ForceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ForceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromDecanewtons(double decanewtons) - { - double value = (double) decanewtons; - return new Force(value, ForceUnit.Decanewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromDyne(double dyne) - { - double value = (double) dyne; - return new Force(value, ForceUnit.Dyn); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilogramsForce(double kilogramsforce) - { - double value = (double) kilogramsforce; - return new Force(value, ForceUnit.KilogramForce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilonewtons(double kilonewtons) - { - double value = (double) kilonewtons; - return new Force(value, ForceUnit.Kilonewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKiloPonds(double kiloponds) - { - double value = (double) kiloponds; - return new Force(value, ForceUnit.KiloPond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromKilopoundsForce(double kilopoundsforce) - { - double value = (double) kilopoundsforce; - return new Force(value, ForceUnit.KilopoundForce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMeganewtons(double meganewtons) - { - double value = (double) meganewtons; - return new Force(value, ForceUnit.Meganewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMicronewtons(double micronewtons) - { - double value = (double) micronewtons; - return new Force(value, ForceUnit.Micronewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromMillinewtons(double millinewtons) - { - double value = (double) millinewtons; - return new Force(value, ForceUnit.Millinewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromNewtons(double newtons) - { - double value = (double) newtons; - return new Force(value, ForceUnit.Newton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromOunceForce(double ounceforce) - { - double value = (double) ounceforce; - return new Force(value, ForceUnit.OunceForce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromPoundals(double poundals) - { - double value = (double) poundals; - return new Force(value, ForceUnit.Poundal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromPoundsForce(double poundsforce) - { - double value = (double) poundsforce; - return new Force(value, ForceUnit.PoundForce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromShortTonsForce(double shorttonsforce) - { - double value = (double) shorttonsforce; - return new Force(value, ForceUnit.ShortTonForce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Force FromTonnesForce(double tonnesforce) - { - double value = (double) tonnesforce; - return new Force(value, ForceUnit.TonneForce); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Force unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Force From(double value, ForceUnit fromUnit) - { - return new Force((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Force Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Force Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Force result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Force result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ForceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ForceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Force objForce)) throw new ArgumentException("Expected type Force.", nameof(obj)); - - return CompareTo(objForce); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Force other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Force objForce)) - return false; - - return Equals(objForce); - } - - public bool Equals(Force other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Force within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Force other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Force. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ForceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Force to another Force with the unit representation . - /// - /// A Force with the specified unit. - public Force ToUnit(ForceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Force(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ForceUnit.Decanewton: return (_value) * 1e1d; - case ForceUnit.Dyn: return _value / 1e5; - case ForceUnit.KilogramForce: return _value * 9.80665002864; - case ForceUnit.Kilonewton: return (_value) * 1e3d; - case ForceUnit.KiloPond: return _value * 9.80665002864; - case ForceUnit.KilopoundForce: return (_value * 4.4482216152605095551842641431421) * 1e3d; - case ForceUnit.Meganewton: return (_value) * 1e6d; - case ForceUnit.Micronewton: return (_value) * 1e-6d; - case ForceUnit.Millinewton: return (_value) * 1e-3d; - case ForceUnit.Newton: return _value; - case ForceUnit.OunceForce: return _value * 2.780138509537812e-1; - case ForceUnit.Poundal: return _value * 0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return _value * 4.4482216152605095551842641431421; - case ForceUnit.ShortTonForce: return _value * 8.896443230521e3; - case ForceUnit.TonneForce: return _value * 9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; - case ForceUnit.Dyn: return baseUnitValue * 1e5; - case ForceUnit.KilogramForce: return baseUnitValue / 9.80665002864; - case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; - case ForceUnit.KiloPond: return baseUnitValue / 9.80665002864; - case ForceUnit.KilopoundForce: return (baseUnitValue / 4.4482216152605095551842641431421) / 1e3d; - case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; - case ForceUnit.Micronewton: return (baseUnitValue) / 1e-6d; - case ForceUnit.Millinewton: return (baseUnitValue) / 1e-3d; - case ForceUnit.Newton: return baseUnitValue; - case ForceUnit.OunceForce: return baseUnitValue / 2.780138509537812e-1; - case ForceUnit.Poundal: return baseUnitValue / 0.13825502798973041652092282466083; - case ForceUnit.PoundForce: return baseUnitValue / 4.4482216152605095551842641431421; - case ForceUnit.ShortTonForce: return baseUnitValue / 8.896443230521e3; - case ForceUnit.TonneForce: return baseUnitValue / 9.80665002864e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.g.cs deleted file mode 100644 index 2843146dd0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ /dev/null @@ -1,859 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ForceChangeRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForceChangeRateUnit? _unit; - - static ForceChangeRate() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); - BaseUnit = ForceChangeRateUnit.NewtonPerSecond; - MaxValue = new ForceChangeRate(double.MaxValue, BaseUnit); - MinValue = new ForceChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.ForceChangeRate; - Units = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); - Zero = new ForceChangeRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ForceChangeRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ForceChangeRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ForceChangeRate(double value, ForceChangeRateUnit unit) - { - if (unit == ForceChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. - /// - public static ForceChangeRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ForceChangeRate - /// - public static ForceChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of ForceChangeRate - /// - public static ForceChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ForceChangeRate quantity. - /// - public static ForceChangeRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. - /// - public static ForceChangeRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ForceChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerMinute => As(ForceChangeRateUnit.KilopoundForcePerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerSecond => As(ForceChangeRateUnit.KilopoundForcePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerMinute => As(ForceChangeRateUnit.PoundForcePerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerSecond => As(ForceChangeRateUnit.PoundForcePerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ForceChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromCentinewtonsPerSecond(double centinewtonspersecond) - { - double value = (double) centinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecanewtonsPerMinute(double decanewtonsperminute) - { - double value = (double) decanewtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecanewtonsPerSecond(double decanewtonspersecond) - { - double value = (double) decanewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromDecinewtonsPerSecond(double decinewtonspersecond) - { - double value = (double) decinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilonewtonsPerMinute(double kilonewtonsperminute) - { - double value = (double) kilonewtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilonewtonsPerSecond(double kilonewtonspersecond) - { - double value = (double) kilonewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilopoundsForcePerMinute(double kilopoundsforceperminute) - { - double value = (double) kilopoundsforceperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromKilopoundsForcePerSecond(double kilopoundsforcepersecond) - { - double value = (double) kilopoundsforcepersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromMicronewtonsPerSecond(double micronewtonspersecond) - { - double value = (double) micronewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromMillinewtonsPerSecond(double millinewtonspersecond) - { - double value = (double) millinewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNanonewtonsPerSecond(double nanonewtonspersecond) - { - double value = (double) nanonewtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNewtonsPerMinute(double newtonsperminute) - { - double value = (double) newtonsperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromNewtonsPerSecond(double newtonspersecond) - { - double value = (double) newtonspersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromPoundsForcePerMinute(double poundsforceperminute) - { - double value = (double) poundsforceperminute; - return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForceChangeRate FromPoundsForcePerSecond(double poundsforcepersecond) - { - double value = (double) poundsforcepersecond; - return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ForceChangeRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) - { - return new ForceChangeRate((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ForceChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ForceChangeRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ForceChangeRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForceChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ForceChangeRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ForceChangeRate objForceChangeRate)) throw new ArgumentException("Expected type ForceChangeRate.", nameof(obj)); - - return CompareTo(objForceChangeRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ForceChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ForceChangeRate objForceChangeRate)) - return false; - - return Equals(objForceChangeRate); - } - - public bool Equals(ForceChangeRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ForceChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ForceChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForceChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ForceChangeRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceChangeRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . - /// - /// A ForceChangeRate with the specified unit. - public ForceChangeRate ToUnit(ForceChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ForceChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (_value / 60) * 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (_value / 60) * 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; - case ForceChangeRateUnit.KilopoundForcePerMinute: return (_value * 4.4482216152605095551842641431421 / 60) * 1e3d; - case ForceChangeRateUnit.KilopoundForcePerSecond: return (_value * 4.4482216152605095551842641431421) * 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return _value / 60; - case ForceChangeRateUnit.NewtonPerSecond: return _value; - case ForceChangeRateUnit.PoundForcePerMinute: return _value * 4.4482216152605095551842641431421 / 60; - case ForceChangeRateUnit.PoundForcePerSecond: return _value * 4.4482216152605095551842641431421; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForceChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; - case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue * 60) / 1e1d; - case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; - case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; - case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue * 60) / 1e3d; - case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; - case ForceChangeRateUnit.KilopoundForcePerMinute: return (baseUnitValue / 4.4482216152605095551842641431421 * 60) / 1e3d; - case ForceChangeRateUnit.KilopoundForcePerSecond: return (baseUnitValue / 4.4482216152605095551842641431421) / 1e3d; - case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; - case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; - case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; - case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue * 60; - case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; - case ForceChangeRateUnit.PoundForcePerMinute: return baseUnitValue / 4.4482216152605095551842641431421 * 60; - case ForceChangeRateUnit.PoundForcePerSecond: return baseUnitValue / 4.4482216152605095551842641431421; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.g.cs deleted file mode 100644 index 276a306d43..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ForcePerLength.g.cs +++ /dev/null @@ -1,1302 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The magnitude of force per unit length. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ForcePerLength : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ForcePerLengthUnit? _unit; - - static ForcePerLength() - { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - BaseUnit = ForcePerLengthUnit.NewtonPerMeter; - MaxValue = new ForcePerLength(double.MaxValue, BaseUnit); - MinValue = new ForcePerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.ForcePerLength; - Units = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); - Zero = new ForcePerLength(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ForcePerLength, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ForcePerLength() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ForcePerLength(double value, ForcePerLengthUnit unit) - { - if (unit == ForcePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. - /// - public static ForcePerLengthUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ForcePerLength - /// - public static ForcePerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of ForcePerLength - /// - public static ForcePerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ForcePerLength quantity. - /// - public static ForcePerLengthUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. - /// - public static ForcePerLength Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ForcePerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonsPerCentimeter => As(ForcePerLengthUnit.CentinewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonsPerMillimeter => As(ForcePerLengthUnit.CentinewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonsPerCentimeter => As(ForcePerLengthUnit.DecanewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonsPerMeter => As(ForcePerLengthUnit.DecanewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonsPerMillimeter => As(ForcePerLengthUnit.DecanewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonsPerCentimeter => As(ForcePerLengthUnit.DecinewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonsPerMillimeter => As(ForcePerLengthUnit.DecinewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerCentimeter => As(ForcePerLengthUnit.KilogramForcePerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerMillimeter => As(ForcePerLengthUnit.KilogramForcePerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerCentimeter => As(ForcePerLengthUnit.KilonewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerMillimeter => As(ForcePerLengthUnit.KilonewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerFoot => As(ForcePerLengthUnit.KilopoundForcePerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerInch => As(ForcePerLengthUnit.KilopoundForcePerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonsPerCentimeter => As(ForcePerLengthUnit.MeganewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonsPerMillimeter => As(ForcePerLengthUnit.MeganewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonsPerCentimeter => As(ForcePerLengthUnit.MicronewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonsPerMillimeter => As(ForcePerLengthUnit.MicronewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonsPerCentimeter => As(ForcePerLengthUnit.MillinewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonsPerMillimeter => As(ForcePerLengthUnit.MillinewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonsPerCentimeter => As(ForcePerLengthUnit.NanonewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonsPerMillimeter => As(ForcePerLengthUnit.NanonewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerCentimeter => As(ForcePerLengthUnit.NewtonPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerMillimeter => As(ForcePerLengthUnit.NewtonPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerFoot => As(ForcePerLengthUnit.PoundForcePerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerInch => As(ForcePerLengthUnit.PoundForcePerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerYard => As(ForcePerLengthUnit.PoundForcePerYard); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerCentimeter => As(ForcePerLengthUnit.TonneForcePerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerMeter => As(ForcePerLengthUnit.TonneForcePerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerMillimeter => As(ForcePerLengthUnit.TonneForcePerMillimeter); - - #endregion - - #region Static Methods - - 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[]{"тс/мм"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ForcePerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromCentinewtonsPerCentimeter(double centinewtonspercentimeter) - { - double value = (double) centinewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromCentinewtonsPerMeter(double centinewtonspermeter) - { - double value = (double) centinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromCentinewtonsPerMillimeter(double centinewtonspermillimeter) - { - double value = (double) centinewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecanewtonsPerCentimeter(double decanewtonspercentimeter) - { - double value = (double) decanewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecanewtonsPerMeter(double decanewtonspermeter) - { - double value = (double) decanewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecanewtonsPerMillimeter(double decanewtonspermillimeter) - { - double value = (double) decanewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecinewtonsPerCentimeter(double decinewtonspercentimeter) - { - double value = (double) decinewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecinewtonsPerMeter(double decinewtonspermeter) - { - double value = (double) decinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromDecinewtonsPerMillimeter(double decinewtonspermillimeter) - { - double value = (double) decinewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilogramsForcePerCentimeter(double kilogramsforcepercentimeter) - { - double value = (double) kilogramsforcepercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilogramsForcePerMeter(double kilogramsforcepermeter) - { - double value = (double) kilogramsforcepermeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilogramsForcePerMillimeter(double kilogramsforcepermillimeter) - { - double value = (double) kilogramsforcepermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilonewtonsPerCentimeter(double kilonewtonspercentimeter) - { - double value = (double) kilonewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilonewtonsPerMeter(double kilonewtonspermeter) - { - double value = (double) kilonewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilonewtonsPerMillimeter(double kilonewtonspermillimeter) - { - double value = (double) kilonewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilopoundsForcePerFoot(double kilopoundsforceperfoot) - { - double value = (double) kilopoundsforceperfoot; - return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromKilopoundsForcePerInch(double kilopoundsforceperinch) - { - double value = (double) kilopoundsforceperinch; - return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMeganewtonsPerCentimeter(double meganewtonspercentimeter) - { - double value = (double) meganewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMeganewtonsPerMeter(double meganewtonspermeter) - { - double value = (double) meganewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMeganewtonsPerMillimeter(double meganewtonspermillimeter) - { - double value = (double) meganewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMicronewtonsPerCentimeter(double micronewtonspercentimeter) - { - double value = (double) micronewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMicronewtonsPerMeter(double micronewtonspermeter) - { - double value = (double) micronewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMicronewtonsPerMillimeter(double micronewtonspermillimeter) - { - double value = (double) micronewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMillinewtonsPerCentimeter(double millinewtonspercentimeter) - { - double value = (double) millinewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMillinewtonsPerMeter(double millinewtonspermeter) - { - double value = (double) millinewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromMillinewtonsPerMillimeter(double millinewtonspermillimeter) - { - double value = (double) millinewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNanonewtonsPerCentimeter(double nanonewtonspercentimeter) - { - double value = (double) nanonewtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNanonewtonsPerMeter(double nanonewtonspermeter) - { - double value = (double) nanonewtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNanonewtonsPerMillimeter(double nanonewtonspermillimeter) - { - double value = (double) nanonewtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNewtonsPerCentimeter(double newtonspercentimeter) - { - double value = (double) newtonspercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNewtonsPerMeter(double newtonspermeter) - { - double value = (double) newtonspermeter; - return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromNewtonsPerMillimeter(double newtonspermillimeter) - { - double value = (double) newtonspermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromPoundsForcePerFoot(double poundsforceperfoot) - { - double value = (double) poundsforceperfoot; - return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromPoundsForcePerInch(double poundsforceperinch) - { - double value = (double) poundsforceperinch; - return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromPoundsForcePerYard(double poundsforceperyard) - { - double value = (double) poundsforceperyard; - return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerYard); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromTonnesForcePerCentimeter(double tonnesforcepercentimeter) - { - double value = (double) tonnesforcepercentimeter; - return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromTonnesForcePerMeter(double tonnesforcepermeter) - { - double value = (double) tonnesforcepermeter; - return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ForcePerLength FromTonnesForcePerMillimeter(double tonnesforcepermillimeter) - { - double value = (double) tonnesforcepermillimeter; - return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ForcePerLength unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) - { - return new ForcePerLength((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ForcePerLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ForcePerLength Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ForcePerLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ForcePerLength result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ForcePerLengthUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ForcePerLengthUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ForcePerLength objForcePerLength)) throw new ArgumentException("Expected type ForcePerLength.", nameof(obj)); - - return CompareTo(objForcePerLength); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ForcePerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ForcePerLength objForcePerLength)) - return false; - - return Equals(objForcePerLength); - } - - public bool Equals(ForcePerLength other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ForcePerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ForcePerLength other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForcePerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ForcePerLengthUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForcePerLengthUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ForcePerLength to another ForcePerLength with the unit representation . - /// - /// A ForcePerLength with the specified unit. - public ForcePerLength ToUnit(ForcePerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ForcePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ForcePerLengthUnit.CentinewtonPerCentimeter: return (_value * 1e2) * 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMillimeter: return (_value * 1e3) * 1e-2d; - case ForcePerLengthUnit.DecanewtonPerCentimeter: return (_value * 1e2) * 1e1d; - case ForcePerLengthUnit.DecanewtonPerMeter: return (_value) * 1e1d; - case ForcePerLengthUnit.DecanewtonPerMillimeter: return (_value * 1e3) * 1e1d; - case ForcePerLengthUnit.DecinewtonPerCentimeter: return (_value * 1e2) * 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMillimeter: return (_value * 1e3) * 1e-1d; - case ForcePerLengthUnit.KilogramForcePerCentimeter: return _value * 980.665002864; - case ForcePerLengthUnit.KilogramForcePerMeter: return _value * 9.80665002864; - case ForcePerLengthUnit.KilogramForcePerMillimeter: return _value * 9.80665002864e3; - case ForcePerLengthUnit.KilonewtonPerCentimeter: return (_value * 1e2) * 1e3d; - case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; - case ForcePerLengthUnit.KilonewtonPerMillimeter: return (_value * 1e3) * 1e3d; - case ForcePerLengthUnit.KilopoundForcePerFoot: return _value * 14593.90292; - case ForcePerLengthUnit.KilopoundForcePerInch: return _value * 1.75126835e5; - case ForcePerLengthUnit.MeganewtonPerCentimeter: return (_value * 1e2) * 1e6d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; - case ForcePerLengthUnit.MeganewtonPerMillimeter: return (_value * 1e3) * 1e6d; - case ForcePerLengthUnit.MicronewtonPerCentimeter: return (_value * 1e2) * 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMillimeter: return (_value * 1e3) * 1e-6d; - case ForcePerLengthUnit.MillinewtonPerCentimeter: return (_value * 1e2) * 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMillimeter: return (_value * 1e3) * 1e-3d; - case ForcePerLengthUnit.NanonewtonPerCentimeter: return (_value * 1e2) * 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMillimeter: return (_value * 1e3) * 1e-9d; - case ForcePerLengthUnit.NewtonPerCentimeter: return _value * 1e2; - case ForcePerLengthUnit.NewtonPerMeter: return _value; - case ForcePerLengthUnit.NewtonPerMillimeter: return _value * 1e3; - case ForcePerLengthUnit.PoundForcePerFoot: return _value * 14.59390292; - case ForcePerLengthUnit.PoundForcePerInch: return _value * 1.75126835e2; - case ForcePerLengthUnit.PoundForcePerYard: return _value * 4.864634307; - case ForcePerLengthUnit.TonneForcePerCentimeter: return _value * 9.80665002864e5; - case ForcePerLengthUnit.TonneForcePerMeter: return _value * 9.80665002864e3; - case ForcePerLengthUnit.TonneForcePerMillimeter: return _value * 9.80665002864e6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ForcePerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ForcePerLengthUnit.CentinewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; - case ForcePerLengthUnit.CentinewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e-2d; - case ForcePerLengthUnit.DecanewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e1d; - case ForcePerLengthUnit.DecanewtonPerMeter: return (baseUnitValue) / 1e1d; - case ForcePerLengthUnit.DecanewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e1d; - case ForcePerLengthUnit.DecinewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; - case ForcePerLengthUnit.DecinewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e-1d; - case ForcePerLengthUnit.KilogramForcePerCentimeter: return baseUnitValue / 980.665002864; - case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue / 9.80665002864; - case ForcePerLengthUnit.KilogramForcePerMillimeter: return baseUnitValue / 9.80665002864e3; - case ForcePerLengthUnit.KilonewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e3d; - case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; - case ForcePerLengthUnit.KilonewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e3d; - case ForcePerLengthUnit.KilopoundForcePerFoot: return baseUnitValue / 14593.90292; - case ForcePerLengthUnit.KilopoundForcePerInch: return baseUnitValue / 1.75126835e5; - case ForcePerLengthUnit.MeganewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e6d; - case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; - case ForcePerLengthUnit.MeganewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e6d; - case ForcePerLengthUnit.MicronewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; - case ForcePerLengthUnit.MicronewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e-6d; - case ForcePerLengthUnit.MillinewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; - case ForcePerLengthUnit.MillinewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e-3d; - case ForcePerLengthUnit.NanonewtonPerCentimeter: return (baseUnitValue / 1e2) / 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; - case ForcePerLengthUnit.NanonewtonPerMillimeter: return (baseUnitValue / 1e3) / 1e-9d; - case ForcePerLengthUnit.NewtonPerCentimeter: return baseUnitValue / 1e2; - case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; - case ForcePerLengthUnit.NewtonPerMillimeter: return baseUnitValue / 1e3; - case ForcePerLengthUnit.PoundForcePerFoot: return baseUnitValue / 14.59390292; - case ForcePerLengthUnit.PoundForcePerInch: return baseUnitValue / 1.75126835e2; - case ForcePerLengthUnit.PoundForcePerYard: return baseUnitValue / 4.864634307; - case ForcePerLengthUnit.TonneForcePerCentimeter: return baseUnitValue / 9.80665002864e5; - case ForcePerLengthUnit.TonneForcePerMeter: return baseUnitValue / 9.80665002864e3; - case ForcePerLengthUnit.TonneForcePerMillimeter: return baseUnitValue / 9.80665002864e6; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.g.cs deleted file mode 100644 index 62796e495f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Frequency.g.cs +++ /dev/null @@ -1,790 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The number of occurrences of a repeating event per unit time. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Frequency : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly FrequencyUnit? _unit; - - static Frequency() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = FrequencyUnit.Hertz; - MaxValue = new Frequency(double.MaxValue, BaseUnit); - MinValue = new Frequency(double.MinValue, BaseUnit); - QuantityType = QuantityType.Frequency; - Units = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); - Zero = new Frequency(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Frequency, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Hertz. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Frequency() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Frequency(double value, FrequencyUnit unit) - { - if (unit == FrequencyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Frequency, which is Hertz. All conversions go via this value. - /// - public static FrequencyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Frequency - /// - public static Frequency MaxValue { get; } - - /// - /// Represents the smallest possible value of Frequency - /// - public static Frequency MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Frequency quantity. - /// - public static FrequencyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. - /// - public static Frequency Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Frequency.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Frequency.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BeatsPerMinute => As(FrequencyUnit.BeatPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double BUnits => As(FrequencyUnit.BUnit); - - /// - /// Gets a value of this quantity converted into - /// - public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigahertz => As(FrequencyUnit.Gigahertz); - - /// - /// Gets a value of this quantity converted into - /// - public double Hertz => As(FrequencyUnit.Hertz); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilohertz => As(FrequencyUnit.Kilohertz); - - /// - /// Gets a value of this quantity converted into - /// - public double Megahertz => As(FrequencyUnit.Megahertz); - - /// - /// Gets a value of this quantity converted into - /// - public double PerSecond => As(FrequencyUnit.PerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Terahertz => As(FrequencyUnit.Terahertz); - - #endregion - - #region Static Methods - - 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[]{"ТГц"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(FrequencyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromBeatsPerMinute(double beatsperminute) - { - double value = (double) beatsperminute; - return new Frequency(value, FrequencyUnit.BeatPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromBUnits(double bunits) - { - double value = (double) bunits; - return new Frequency(value, FrequencyUnit.BUnit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromCyclesPerHour(double cyclesperhour) - { - double value = (double) cyclesperhour; - return new Frequency(value, FrequencyUnit.CyclePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromCyclesPerMinute(double cyclesperminute) - { - double value = (double) cyclesperminute; - return new Frequency(value, FrequencyUnit.CyclePerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromGigahertz(double gigahertz) - { - double value = (double) gigahertz; - return new Frequency(value, FrequencyUnit.Gigahertz); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromHertz(double hertz) - { - double value = (double) hertz; - return new Frequency(value, FrequencyUnit.Hertz); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromKilohertz(double kilohertz) - { - double value = (double) kilohertz; - return new Frequency(value, FrequencyUnit.Kilohertz); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromMegahertz(double megahertz) - { - double value = (double) megahertz; - return new Frequency(value, FrequencyUnit.Megahertz); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromPerSecond(double persecond) - { - double value = (double) persecond; - return new Frequency(value, FrequencyUnit.PerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromRadiansPerSecond(double radianspersecond) - { - double value = (double) radianspersecond; - return new Frequency(value, FrequencyUnit.RadianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Frequency FromTerahertz(double terahertz) - { - double value = (double) terahertz; - return new Frequency(value, FrequencyUnit.Terahertz); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Frequency unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Frequency From(double value, FrequencyUnit fromUnit) - { - return new Frequency((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Frequency Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Frequency Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Frequency result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Frequency result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FrequencyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out FrequencyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out FrequencyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Frequency objFrequency)) throw new ArgumentException("Expected type Frequency.", nameof(obj)); - - return CompareTo(objFrequency); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Frequency other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Frequency objFrequency)) - return false; - - return Equals(objFrequency); - } - - public bool Equals(Frequency other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Frequency within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Frequency other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Frequency. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((FrequencyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FrequencyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Frequency to another Frequency with the unit representation . - /// - /// A Frequency with the specified unit. - public Frequency ToUnit(FrequencyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Frequency(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case FrequencyUnit.BeatPerMinute: return _value / 60; - case FrequencyUnit.BUnit: return Math.Sqrt(_value * 1e3); - case FrequencyUnit.CyclePerHour: return _value / 3600; - case FrequencyUnit.CyclePerMinute: return _value / 60; - case FrequencyUnit.Gigahertz: return (_value) * 1e9d; - case FrequencyUnit.Hertz: return _value; - case FrequencyUnit.Kilohertz: return (_value) * 1e3d; - case FrequencyUnit.Megahertz: return (_value) * 1e6d; - case FrequencyUnit.PerSecond: return _value; - case FrequencyUnit.RadianPerSecond: return _value / 6.2831853072; - case FrequencyUnit.Terahertz: return (_value) * 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(FrequencyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case FrequencyUnit.BeatPerMinute: return baseUnitValue * 60; - case FrequencyUnit.BUnit: return baseUnitValue * baseUnitValue * 1e-3; - case FrequencyUnit.CyclePerHour: return baseUnitValue * 3600; - case FrequencyUnit.CyclePerMinute: return baseUnitValue * 60; - case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; - case FrequencyUnit.Hertz: return baseUnitValue; - case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; - case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; - case FrequencyUnit.PerSecond: return baseUnitValue; - case FrequencyUnit.RadianPerSecond: return baseUnitValue * 6.2831853072; - case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs deleted file mode 100644 index 49b74a2828..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ /dev/null @@ -1,653 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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). - /// - /// - /// https://en.wikipedia.org/wiki/Fuel_efficiency - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class FuelEfficiency : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly FuelEfficiencyUnit? _unit; - - static FuelEfficiency() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = FuelEfficiencyUnit.LiterPer100Kilometers; - MaxValue = new FuelEfficiency(double.MaxValue, BaseUnit); - MinValue = new FuelEfficiency(double.MinValue, BaseUnit); - QuantityType = QuantityType.FuelEfficiency; - Units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast().Except(new FuelEfficiencyUnit[]{ FuelEfficiencyUnit.Undefined }).ToArray(); - Zero = new FuelEfficiency(0, BaseUnit); - Info = new QuantityInfo(QuantityType.FuelEfficiency, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit LiterPer100Kilometers. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public FuelEfficiency() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private FuelEfficiency(double value, FuelEfficiencyUnit unit) - { - if (unit == FuelEfficiencyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of FuelEfficiency, which is LiterPer100Kilometers. All conversions go via this value. - /// - public static FuelEfficiencyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of FuelEfficiency - /// - public static FuelEfficiency MaxValue { get; } - - /// - /// Represents the smallest possible value of FuelEfficiency - /// - public static FuelEfficiency MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the FuelEfficiency quantity. - /// - public static FuelEfficiencyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit LiterPer100Kilometers. - /// - public static FuelEfficiency Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => FuelEfficiency.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => FuelEfficiency.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); - - /// - /// Gets a value of this quantity converted into - /// - public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); - - #endregion - - #region Static Methods - - 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.)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(FuelEfficiencyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(FuelEfficiencyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static FuelEfficiency FromKilometersPerLiters(double kilometersperliters) - { - double value = (double) kilometersperliters; - return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static FuelEfficiency FromLitersPer100Kilometers(double litersper100kilometers) - { - double value = (double) litersper100kilometers; - return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static FuelEfficiency FromMilesPerUkGallon(double milesperukgallon) - { - double value = (double) milesperukgallon; - return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static FuelEfficiency FromMilesPerUsGallon(double milesperusgallon) - { - double value = (double) milesperusgallon; - return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// FuelEfficiency unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static FuelEfficiency From(double value, FuelEfficiencyUnit fromUnit) - { - return new FuelEfficiency((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static FuelEfficiency Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static FuelEfficiency Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out FuelEfficiency result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out FuelEfficiency result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static FuelEfficiencyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static FuelEfficiencyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out FuelEfficiencyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out FuelEfficiencyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is FuelEfficiency objFuelEfficiency)) throw new ArgumentException("Expected type FuelEfficiency.", nameof(obj)); - - return CompareTo(objFuelEfficiency); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(FuelEfficiency other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is FuelEfficiency objFuelEfficiency)) - return false; - - return Equals(objFuelEfficiency); - } - - public bool Equals(FuelEfficiency other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current FuelEfficiency. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((FuelEfficiencyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FuelEfficiencyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation . - /// - /// A FuelEfficiency with the specified unit. - public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new FuelEfficiency(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case FuelEfficiencyUnit.KilometerPerLiter: return 100 / _value; - case FuelEfficiencyUnit.LiterPer100Kilometers: return _value; - case FuelEfficiencyUnit.MilePerUkGallon: return (100 * 4.54609188) / (1.609344 * _value); - case FuelEfficiencyUnit.MilePerUsGallon: return (100 * 3.785411784) / (1.609344 * _value); - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(FuelEfficiencyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case FuelEfficiencyUnit.KilometerPerLiter: return 100 / baseUnitValue; - case FuelEfficiencyUnit.LiterPer100Kilometers: return baseUnitValue; - case FuelEfficiencyUnit.MilePerUkGallon: return (100 * 4.54609188) / (1.609344 * baseUnitValue); - case FuelEfficiencyUnit.MilePerUsGallon: return (100 * 3.785411784) / (1.609344 * baseUnitValue); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.g.cs deleted file mode 100644 index 13342da5f8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatFlux.g.cs +++ /dev/null @@ -1,916 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Heat flux is the flow of energy per unit of area per unit of time - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class HeatFlux : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly HeatFluxUnit? _unit; - - static HeatFlux() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - BaseUnit = HeatFluxUnit.WattPerSquareMeter; - MaxValue = new HeatFlux(double.MaxValue, BaseUnit); - MinValue = new HeatFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.HeatFlux; - Units = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); - Zero = new HeatFlux(0, BaseUnit); - Info = new QuantityInfo(QuantityType.HeatFlux, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public HeatFlux() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private HeatFlux(double value, HeatFluxUnit unit) - { - if (unit == HeatFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. - /// - public static HeatFluxUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of HeatFlux - /// - public static HeatFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of HeatFlux - /// - public static HeatFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the HeatFlux quantity. - /// - public static HeatFluxUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - public static HeatFlux Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => HeatFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => HeatFlux.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(HeatFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(HeatFluxUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerHourSquareFoot(double btusperhoursquarefoot) - { - double value = (double) btusperhoursquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerMinuteSquareFoot(double btusperminutesquarefoot) - { - double value = (double) btusperminutesquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerSecondSquareFoot(double btuspersecondsquarefoot) - { - double value = (double) btuspersecondsquarefoot; - return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromBtusPerSecondSquareInch(double btuspersecondsquareinch) - { - double value = (double) btuspersecondsquareinch; - return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double caloriespersecondsquarecentimeter) - { - double value = (double) caloriespersecondsquarecentimeter; - return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromCentiwattsPerSquareMeter(double centiwattspersquaremeter) - { - double value = (double) centiwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromDeciwattsPerSquareMeter(double deciwattspersquaremeter) - { - double value = (double) deciwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilocaloriesPerHourSquareMeter(double kilocaloriesperhoursquaremeter) - { - double value = (double) kilocaloriesperhoursquaremeter; - return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double kilocaloriespersecondsquarecentimeter) - { - double value = (double) kilocaloriespersecondsquarecentimeter; - return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromKilowattsPerSquareMeter(double kilowattspersquaremeter) - { - double value = (double) kilowattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromMicrowattsPerSquareMeter(double microwattspersquaremeter) - { - double value = (double) microwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) - { - double value = (double) milliwattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromNanowattsPerSquareMeter(double nanowattspersquaremeter) - { - double value = (double) nanowattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromPoundsForcePerFootSecond(double poundsforceperfootsecond) - { - double value = (double) poundsforceperfootsecond; - return new HeatFlux(value, HeatFluxUnit.PoundForcePerFootSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromPoundsPerSecondCubed(double poundspersecondcubed) - { - double value = (double) poundspersecondcubed; - return new HeatFlux(value, HeatFluxUnit.PoundPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareFoot(double wattspersquarefoot) - { - double value = (double) wattspersquarefoot; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareInch(double wattspersquareinch) - { - double value = (double) wattspersquareinch; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatFlux FromWattsPerSquareMeter(double wattspersquaremeter) - { - double value = (double) wattspersquaremeter; - return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// HeatFlux unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static HeatFlux From(double value, HeatFluxUnit fromUnit) - { - return new HeatFlux((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static HeatFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static HeatFlux Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out HeatFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out HeatFlux result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatFluxUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static HeatFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out HeatFluxUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out HeatFluxUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is HeatFlux objHeatFlux)) throw new ArgumentException("Expected type HeatFlux.", nameof(obj)); - - return CompareTo(objHeatFlux); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(HeatFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is HeatFlux objHeatFlux)) - return false; - - return Equals(objHeatFlux); - } - - public bool Equals(HeatFlux other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another HeatFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((HeatFluxUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatFluxUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this HeatFlux to another HeatFlux with the unit representation . - /// - /// A HeatFlux with the specified unit. - public HeatFlux ToUnit(HeatFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new HeatFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return _value * 3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return _value * 1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return _value * 1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return _value * 1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return _value * 4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (_value) * 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (_value) * 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return _value * 1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (_value * 4.1868e4) * 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (_value) * 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (_value) * 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (_value) * 1e-9d; - case HeatFluxUnit.PoundForcePerFootSecond: return _value * 1.459390293720636e1; - case HeatFluxUnit.PoundPerSecondCubed: return _value * 4.5359237e-1; - case HeatFluxUnit.WattPerSquareFoot: return _value * 1.07639e1; - case HeatFluxUnit.WattPerSquareInch: return _value * 1.5500031e3; - case HeatFluxUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(HeatFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case HeatFluxUnit.BtuPerHourSquareFoot: return baseUnitValue / 3.15459075; - case HeatFluxUnit.BtuPerMinuteSquareFoot: return baseUnitValue / 1.89275445e2; - case HeatFluxUnit.BtuPerSecondSquareFoot: return baseUnitValue / 1.13565267e4; - case HeatFluxUnit.BtuPerSecondSquareInch: return baseUnitValue / 1.63533984e6; - case HeatFluxUnit.CaloriePerSecondSquareCentimeter: return baseUnitValue / 4.1868e4; - case HeatFluxUnit.CentiwattPerSquareMeter: return (baseUnitValue) / 1e-2d; - case HeatFluxUnit.DeciwattPerSquareMeter: return (baseUnitValue) / 1e-1d; - case HeatFluxUnit.KilocaloriePerHourSquareMeter: return baseUnitValue / 1.163; - case HeatFluxUnit.KilocaloriePerSecondSquareCentimeter: return (baseUnitValue / 4.1868e4) / 1e3d; - case HeatFluxUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case HeatFluxUnit.MicrowattPerSquareMeter: return (baseUnitValue) / 1e-6d; - case HeatFluxUnit.MilliwattPerSquareMeter: return (baseUnitValue) / 1e-3d; - case HeatFluxUnit.NanowattPerSquareMeter: return (baseUnitValue) / 1e-9d; - case HeatFluxUnit.PoundForcePerFootSecond: return baseUnitValue / 1.459390293720636e1; - case HeatFluxUnit.PoundPerSecondCubed: return baseUnitValue / 4.5359237e-1; - case HeatFluxUnit.WattPerSquareFoot: return baseUnitValue / 1.07639e1; - case HeatFluxUnit.WattPerSquareInch: return baseUnitValue / 1.5500031e3; - case HeatFluxUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs deleted file mode 100644 index 808e67e1fe..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class HeatTransferCoefficient : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly HeatTransferCoefficientUnit? _unit; - - static HeatTransferCoefficient() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); - BaseUnit = HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; - MaxValue = new HeatTransferCoefficient(double.MaxValue, BaseUnit); - MinValue = new HeatTransferCoefficient(double.MinValue, BaseUnit); - QuantityType = QuantityType.HeatTransferCoefficient; - Units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); - Zero = new HeatTransferCoefficient(0, BaseUnit); - Info = new QuantityInfo(QuantityType.HeatTransferCoefficient, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public HeatTransferCoefficient() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private HeatTransferCoefficient(double value, HeatTransferCoefficientUnit unit) - { - if (unit == HeatTransferCoefficientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. - /// - public static HeatTransferCoefficientUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of HeatTransferCoefficient - /// - public static HeatTransferCoefficient MaxValue { get; } - - /// - /// Represents the smallest possible value of HeatTransferCoefficient - /// - public static HeatTransferCoefficient MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the HeatTransferCoefficient quantity. - /// - public static HeatTransferCoefficientUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. - /// - public static HeatTransferCoefficient Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => HeatTransferCoefficient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerSquareFootDegreeFahrenheit => As(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(HeatTransferCoefficientUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(HeatTransferCoefficientUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromBtusPerSquareFootDegreeFahrenheit(double btuspersquarefootdegreefahrenheit) - { - double value = (double) btuspersquarefootdegreefahrenheit; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double wattspersquaremetercelsius) - { - double value = (double) wattspersquaremetercelsius; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double wattspersquaremeterkelvin) - { - double value = (double) wattspersquaremeterkelvin; - return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// HeatTransferCoefficient unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static HeatTransferCoefficient From(double value, HeatTransferCoefficientUnit fromUnit) - { - return new HeatTransferCoefficient((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static HeatTransferCoefficient Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static HeatTransferCoefficient Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out HeatTransferCoefficient result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out HeatTransferCoefficient result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static HeatTransferCoefficientUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static HeatTransferCoefficientUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out HeatTransferCoefficientUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is HeatTransferCoefficient objHeatTransferCoefficient)) throw new ArgumentException("Expected type HeatTransferCoefficient.", nameof(obj)); - - return CompareTo(objHeatTransferCoefficient); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(HeatTransferCoefficient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is HeatTransferCoefficient objHeatTransferCoefficient)) - return false; - - return Equals(objHeatTransferCoefficient); - } - - public bool Equals(HeatTransferCoefficient other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another HeatTransferCoefficient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatTransferCoefficient. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((HeatTransferCoefficientUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatTransferCoefficientUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . - /// - /// A HeatTransferCoefficient with the specified unit. - public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new HeatTransferCoefficient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit: return _value * 5.6782633411134878; - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return _value; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(HeatTransferCoefficientUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit: return baseUnitValue / 5.6782633411134878; - case HeatTransferCoefficientUnit.WattPerSquareMeterCelsius: return baseUnitValue; - case HeatTransferCoefficientUnit.WattPerSquareMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.g.cs deleted file mode 100644 index 23533f5bfd..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Illuminance.g.cs +++ /dev/null @@ -1,653 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. - /// - /// - /// https://en.wikipedia.org/wiki/Illuminance - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Illuminance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IlluminanceUnit? _unit; - - static Illuminance() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); - BaseUnit = IlluminanceUnit.Lux; - MaxValue = new Illuminance(double.MaxValue, BaseUnit); - MinValue = new Illuminance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Illuminance; - Units = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); - Zero = new Illuminance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Illuminance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Lux. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Illuminance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Illuminance(double value, IlluminanceUnit unit) - { - if (unit == IlluminanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Illuminance, which is Lux. All conversions go via this value. - /// - public static IlluminanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Illuminance - /// - public static Illuminance MaxValue { get; } - - /// - /// Represents the smallest possible value of Illuminance - /// - public static Illuminance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Illuminance quantity. - /// - public static IlluminanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Lux. - /// - public static Illuminance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Illuminance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Illuminance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Kilolux => As(IlluminanceUnit.Kilolux); - - /// - /// Gets a value of this quantity converted into - /// - public double Lux => As(IlluminanceUnit.Lux); - - /// - /// Gets a value of this quantity converted into - /// - public double Megalux => As(IlluminanceUnit.Megalux); - - /// - /// Gets a value of this quantity converted into - /// - public double Millilux => As(IlluminanceUnit.Millilux); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(IlluminanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromKilolux(double kilolux) - { - double value = (double) kilolux; - return new Illuminance(value, IlluminanceUnit.Kilolux); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromLux(double lux) - { - double value = (double) lux; - return new Illuminance(value, IlluminanceUnit.Lux); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromMegalux(double megalux) - { - double value = (double) megalux; - return new Illuminance(value, IlluminanceUnit.Megalux); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Illuminance FromMillilux(double millilux) - { - double value = (double) millilux; - return new Illuminance(value, IlluminanceUnit.Millilux); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Illuminance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Illuminance From(double value, IlluminanceUnit fromUnit) - { - return new Illuminance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Illuminance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Illuminance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Illuminance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Illuminance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IlluminanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out IlluminanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out IlluminanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Illuminance objIlluminance)) throw new ArgumentException("Expected type Illuminance.", nameof(obj)); - - return CompareTo(objIlluminance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Illuminance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Illuminance objIlluminance)) - return false; - - return Equals(objIlluminance); - } - - public bool Equals(Illuminance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Illuminance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Illuminance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Illuminance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((IlluminanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IlluminanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Illuminance to another Illuminance with the unit representation . - /// - /// A Illuminance with the specified unit. - public Illuminance ToUnit(IlluminanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Illuminance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case IlluminanceUnit.Kilolux: return (_value) * 1e3d; - case IlluminanceUnit.Lux: return _value; - case IlluminanceUnit.Megalux: return (_value) * 1e6d; - case IlluminanceUnit.Millilux: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IlluminanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IlluminanceUnit.Kilolux: return (baseUnitValue) / 1e3d; - case IlluminanceUnit.Lux: return baseUnitValue; - case IlluminanceUnit.Megalux: return (baseUnitValue) / 1e6d; - case IlluminanceUnit.Millilux: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.g.cs deleted file mode 100644 index 8d513cf8e8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.g.cs +++ /dev/null @@ -1,1068 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Information : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly InformationUnit? _unit; - - static Information() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = InformationUnit.Bit; - MaxValue = new Information(decimal.MaxValue, BaseUnit); - MinValue = new Information(decimal.MinValue, BaseUnit); - QuantityType = QuantityType.Information; - Units = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); - Zero = new Information(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Information, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Bit. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Information() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Information(decimal value, InformationUnit unit) - { - if (unit == InformationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = value; - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Information, which is Bit. All conversions go via this value. - /// - public static InformationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Information - /// - public static Information MaxValue { get; } - - /// - /// Represents the smallest possible value of Information - /// - public static Information MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Information quantity. - /// - public static InformationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Bit. - /// - public static Information Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Information.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Information.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Bits => As(InformationUnit.Bit); - - /// - /// Gets a value of this quantity converted into - /// - public double Bytes => As(InformationUnit.Byte); - - /// - /// Gets a value of this quantity converted into - /// - public double Exabits => As(InformationUnit.Exabit); - - /// - /// Gets a value of this quantity converted into - /// - public double Exabytes => As(InformationUnit.Exabyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Exbibits => As(InformationUnit.Exbibit); - - /// - /// Gets a value of this quantity converted into - /// - public double Exbibytes => As(InformationUnit.Exbibyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Gibibits => As(InformationUnit.Gibibit); - - /// - /// Gets a value of this quantity converted into - /// - public double Gibibytes => As(InformationUnit.Gibibyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigabits => As(InformationUnit.Gigabit); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigabytes => As(InformationUnit.Gigabyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Kibibits => As(InformationUnit.Kibibit); - - /// - /// Gets a value of this quantity converted into - /// - public double Kibibytes => As(InformationUnit.Kibibyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilobits => As(InformationUnit.Kilobit); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilobytes => As(InformationUnit.Kilobyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Mebibits => As(InformationUnit.Mebibit); - - /// - /// Gets a value of this quantity converted into - /// - public double Mebibytes => As(InformationUnit.Mebibyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Megabits => As(InformationUnit.Megabit); - - /// - /// Gets a value of this quantity converted into - /// - public double Megabytes => As(InformationUnit.Megabyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Pebibits => As(InformationUnit.Pebibit); - - /// - /// Gets a value of this quantity converted into - /// - public double Pebibytes => As(InformationUnit.Pebibyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Petabits => As(InformationUnit.Petabit); - - /// - /// Gets a value of this quantity converted into - /// - public double Petabytes => As(InformationUnit.Petabyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Tebibits => As(InformationUnit.Tebibit); - - /// - /// Gets a value of this quantity converted into - /// - public double Tebibytes => As(InformationUnit.Tebibyte); - - /// - /// Gets a value of this quantity converted into - /// - public double Terabits => As(InformationUnit.Terabit); - - /// - /// Gets a value of this quantity converted into - /// - public double Terabytes => As(InformationUnit.Terabyte); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(InformationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(InformationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromBits(double bits) - { - decimal value = (decimal) bits; - return new Information(value, InformationUnit.Bit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromBytes(double bytes) - { - decimal value = (decimal) bytes; - return new Information(value, InformationUnit.Byte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExabits(double exabits) - { - decimal value = (decimal) exabits; - return new Information(value, InformationUnit.Exabit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExabytes(double exabytes) - { - decimal value = (decimal) exabytes; - return new Information(value, InformationUnit.Exabyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExbibits(double exbibits) - { - decimal value = (decimal) exbibits; - return new Information(value, InformationUnit.Exbibit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromExbibytes(double exbibytes) - { - decimal value = (decimal) exbibytes; - return new Information(value, InformationUnit.Exbibyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGibibits(double gibibits) - { - decimal value = (decimal) gibibits; - return new Information(value, InformationUnit.Gibibit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGibibytes(double gibibytes) - { - decimal value = (decimal) gibibytes; - return new Information(value, InformationUnit.Gibibyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGigabits(double gigabits) - { - decimal value = (decimal) gigabits; - return new Information(value, InformationUnit.Gigabit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromGigabytes(double gigabytes) - { - decimal value = (decimal) gigabytes; - return new Information(value, InformationUnit.Gigabyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKibibits(double kibibits) - { - decimal value = (decimal) kibibits; - return new Information(value, InformationUnit.Kibibit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKibibytes(double kibibytes) - { - decimal value = (decimal) kibibytes; - return new Information(value, InformationUnit.Kibibyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKilobits(double kilobits) - { - decimal value = (decimal) kilobits; - return new Information(value, InformationUnit.Kilobit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromKilobytes(double kilobytes) - { - decimal value = (decimal) kilobytes; - return new Information(value, InformationUnit.Kilobyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMebibits(double mebibits) - { - decimal value = (decimal) mebibits; - return new Information(value, InformationUnit.Mebibit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMebibytes(double mebibytes) - { - decimal value = (decimal) mebibytes; - return new Information(value, InformationUnit.Mebibyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMegabits(double megabits) - { - decimal value = (decimal) megabits; - return new Information(value, InformationUnit.Megabit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromMegabytes(double megabytes) - { - decimal value = (decimal) megabytes; - return new Information(value, InformationUnit.Megabyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPebibits(double pebibits) - { - decimal value = (decimal) pebibits; - return new Information(value, InformationUnit.Pebibit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPebibytes(double pebibytes) - { - decimal value = (decimal) pebibytes; - return new Information(value, InformationUnit.Pebibyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPetabits(double petabits) - { - decimal value = (decimal) petabits; - return new Information(value, InformationUnit.Petabit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromPetabytes(double petabytes) - { - decimal value = (decimal) petabytes; - return new Information(value, InformationUnit.Petabyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTebibits(double tebibits) - { - decimal value = (decimal) tebibits; - return new Information(value, InformationUnit.Tebibit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTebibytes(double tebibytes) - { - decimal value = (decimal) tebibytes; - return new Information(value, InformationUnit.Tebibyte); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTerabits(double terabits) - { - decimal value = (decimal) terabits; - return new Information(value, InformationUnit.Terabit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Information FromTerabytes(double terabytes) - { - decimal value = (decimal) terabytes; - return new Information(value, InformationUnit.Terabyte); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Information unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Information From(double value, InformationUnit fromUnit) - { - return new Information((decimal)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Information Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Information Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Information result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Information result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static InformationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out InformationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out InformationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Information objInformation)) throw new ArgumentException("Expected type Information.", nameof(obj)); - - return CompareTo(objInformation); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Information other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Information objInformation)) - return false; - - return Equals(objInformation); - } - - public bool Equals(Information other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Information within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Information other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Information. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((InformationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(InformationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Information to another Information with the unit representation . - /// - /// A Information with the specified unit. - public Information ToUnit(InformationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Information(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal AsBaseUnit() - { - switch(Unit) - { - case InformationUnit.Bit: return _value; - case InformationUnit.Byte: return _value * 8m; - case InformationUnit.Exabit: return (_value) * 1e18m; - case InformationUnit.Exabyte: return (_value * 8m) * 1e18m; - case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (_value * 8m) * (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (_value) * 1e9m; - case InformationUnit.Gigabyte: return (_value * 8m) * 1e9m; - case InformationUnit.Kibibit: return (_value) * 1024m; - case InformationUnit.Kibibyte: return (_value * 8m) * 1024m; - case InformationUnit.Kilobit: return (_value) * 1e3m; - case InformationUnit.Kilobyte: return (_value * 8m) * 1e3m; - case InformationUnit.Mebibit: return (_value) * (1024m * 1024); - case InformationUnit.Mebibyte: return (_value * 8m) * (1024m * 1024); - case InformationUnit.Megabit: return (_value) * 1e6m; - case InformationUnit.Megabyte: return (_value * 8m) * 1e6m; - case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (_value) * 1e15m; - case InformationUnit.Petabyte: return (_value * 8m) * 1e15m; - case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (_value * 8m) * (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (_value) * 1e12m; - case InformationUnit.Terabyte: return (_value * 8m) * 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(InformationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case InformationUnit.Bit: return baseUnitValue; - case InformationUnit.Byte: return baseUnitValue / 8m; - case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; - case InformationUnit.Exabyte: return (baseUnitValue / 8m) / 1e18m; - case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Exbibyte: return (baseUnitValue / 8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); - case InformationUnit.Gibibyte: return (baseUnitValue / 8m) / (1024m * 1024 * 1024); - case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; - case InformationUnit.Gigabyte: return (baseUnitValue / 8m) / 1e9m; - case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; - case InformationUnit.Kibibyte: return (baseUnitValue / 8m) / 1024m; - case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; - case InformationUnit.Kilobyte: return (baseUnitValue / 8m) / 1e3m; - case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); - case InformationUnit.Mebibyte: return (baseUnitValue / 8m) / (1024m * 1024); - case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; - case InformationUnit.Megabyte: return (baseUnitValue / 8m) / 1e6m; - case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Pebibyte: return (baseUnitValue / 8m) / (1024m * 1024 * 1024 * 1024 * 1024); - case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; - case InformationUnit.Petabyte: return (baseUnitValue / 8m) / 1e15m; - case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Tebibyte: return (baseUnitValue / 8m) / (1024m * 1024 * 1024 * 1024); - case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; - case InformationUnit.Terabyte: return (baseUnitValue / 8m) / 1e12m; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.g.cs deleted file mode 100644 index b46931c56e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiance.g.cs +++ /dev/null @@ -1,840 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Irradiance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IrradianceUnit? _unit; - - static Irradiance() - { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - BaseUnit = IrradianceUnit.WattPerSquareMeter; - MaxValue = new Irradiance(double.MaxValue, BaseUnit); - MinValue = new Irradiance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Irradiance; - Units = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); - Zero = new Irradiance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Irradiance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Irradiance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Irradiance(double value, IrradianceUnit unit) - { - if (unit == IrradianceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. - /// - public static IrradianceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Irradiance - /// - public static Irradiance MaxValue { get; } - - /// - /// Represents the smallest possible value of Irradiance - /// - public static Irradiance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Irradiance quantity. - /// - public static IrradianceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. - /// - public static Irradiance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Irradiance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Irradiance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerSquareCentimeter => As(IrradianceUnit.KilowattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerSquareCentimeter => As(IrradianceUnit.MegawattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerSquareMeter => As(IrradianceUnit.MegawattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerSquareCentimeter => As(IrradianceUnit.MicrowattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerSquareMeter => As(IrradianceUnit.MicrowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerSquareCentimeter => As(IrradianceUnit.MilliwattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerSquareMeter => As(IrradianceUnit.MilliwattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerSquareCentimeter => As(IrradianceUnit.NanowattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerSquareMeter => As(IrradianceUnit.NanowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicowattsPerSquareCentimeter => As(IrradianceUnit.PicowattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicowattsPerSquareMeter => As(IrradianceUnit.PicowattPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareCentimeter => As(IrradianceUnit.WattPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(IrradianceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromKilowattsPerSquareCentimeter(double kilowattspersquarecentimeter) - { - double value = (double) kilowattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.KilowattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) - { - double value = (double) kilowattspersquaremeter; - return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromMegawattsPerSquareCentimeter(double megawattspersquarecentimeter) - { - double value = (double) megawattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.MegawattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromMegawattsPerSquareMeter(double megawattspersquaremeter) - { - double value = (double) megawattspersquaremeter; - return new Irradiance(value, IrradianceUnit.MegawattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromMicrowattsPerSquareCentimeter(double microwattspersquarecentimeter) - { - double value = (double) microwattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.MicrowattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromMicrowattsPerSquareMeter(double microwattspersquaremeter) - { - double value = (double) microwattspersquaremeter; - return new Irradiance(value, IrradianceUnit.MicrowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromMilliwattsPerSquareCentimeter(double milliwattspersquarecentimeter) - { - double value = (double) milliwattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.MilliwattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) - { - double value = (double) milliwattspersquaremeter; - return new Irradiance(value, IrradianceUnit.MilliwattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromNanowattsPerSquareCentimeter(double nanowattspersquarecentimeter) - { - double value = (double) nanowattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.NanowattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromNanowattsPerSquareMeter(double nanowattspersquaremeter) - { - double value = (double) nanowattspersquaremeter; - return new Irradiance(value, IrradianceUnit.NanowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromPicowattsPerSquareCentimeter(double picowattspersquarecentimeter) - { - double value = (double) picowattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.PicowattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromPicowattsPerSquareMeter(double picowattspersquaremeter) - { - double value = (double) picowattspersquaremeter; - return new Irradiance(value, IrradianceUnit.PicowattPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromWattsPerSquareCentimeter(double wattspersquarecentimeter) - { - double value = (double) wattspersquarecentimeter; - return new Irradiance(value, IrradianceUnit.WattPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) - { - double value = (double) wattspersquaremeter; - return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Irradiance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Irradiance From(double value, IrradianceUnit fromUnit) - { - return new Irradiance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Irradiance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Irradiance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Irradiance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Irradiance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradianceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out IrradianceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out IrradianceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Irradiance objIrradiance)) throw new ArgumentException("Expected type Irradiance.", nameof(obj)); - - return CompareTo(objIrradiance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Irradiance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Irradiance objIrradiance)) - return false; - - return Equals(objIrradiance); - } - - public bool Equals(Irradiance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Irradiance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Irradiance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((IrradianceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradianceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Irradiance to another Irradiance with the unit representation . - /// - /// A Irradiance with the specified unit. - public Irradiance ToUnit(IrradianceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Irradiance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case IrradianceUnit.KilowattPerSquareCentimeter: return (_value * 10000) * 1e3d; - case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; - case IrradianceUnit.MegawattPerSquareCentimeter: return (_value * 10000) * 1e6d; - case IrradianceUnit.MegawattPerSquareMeter: return (_value) * 1e6d; - case IrradianceUnit.MicrowattPerSquareCentimeter: return (_value * 10000) * 1e-6d; - case IrradianceUnit.MicrowattPerSquareMeter: return (_value) * 1e-6d; - case IrradianceUnit.MilliwattPerSquareCentimeter: return (_value * 10000) * 1e-3d; - case IrradianceUnit.MilliwattPerSquareMeter: return (_value) * 1e-3d; - case IrradianceUnit.NanowattPerSquareCentimeter: return (_value * 10000) * 1e-9d; - case IrradianceUnit.NanowattPerSquareMeter: return (_value) * 1e-9d; - case IrradianceUnit.PicowattPerSquareCentimeter: return (_value * 10000) * 1e-12d; - case IrradianceUnit.PicowattPerSquareMeter: return (_value) * 1e-12d; - case IrradianceUnit.WattPerSquareCentimeter: return _value * 10000; - case IrradianceUnit.WattPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IrradianceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IrradianceUnit.KilowattPerSquareCentimeter: return (baseUnitValue * 0.0001) / 1e3d; - case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; - case IrradianceUnit.MegawattPerSquareCentimeter: return (baseUnitValue * 0.0001) / 1e6d; - case IrradianceUnit.MegawattPerSquareMeter: return (baseUnitValue) / 1e6d; - case IrradianceUnit.MicrowattPerSquareCentimeter: return (baseUnitValue * 0.0001) / 1e-6d; - case IrradianceUnit.MicrowattPerSquareMeter: return (baseUnitValue) / 1e-6d; - case IrradianceUnit.MilliwattPerSquareCentimeter: return (baseUnitValue * 0.0001) / 1e-3d; - case IrradianceUnit.MilliwattPerSquareMeter: return (baseUnitValue) / 1e-3d; - case IrradianceUnit.NanowattPerSquareCentimeter: return (baseUnitValue * 0.0001) / 1e-9d; - case IrradianceUnit.NanowattPerSquareMeter: return (baseUnitValue) / 1e-9d; - case IrradianceUnit.PicowattPerSquareCentimeter: return (baseUnitValue * 0.0001) / 1e-12d; - case IrradianceUnit.PicowattPerSquareMeter: return (baseUnitValue) / 1e-12d; - case IrradianceUnit.WattPerSquareCentimeter: return baseUnitValue * 0.0001; - case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.g.cs deleted file mode 100644 index c1b78f3f3d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Irradiation.g.cs +++ /dev/null @@ -1,710 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources. - /// - /// - /// https://en.wikipedia.org/wiki/Irradiation - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Irradiation : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly IrradiationUnit? _unit; - - static Irradiation() - { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - BaseUnit = IrradiationUnit.JoulePerSquareMeter; - MaxValue = new Irradiation(double.MaxValue, BaseUnit); - MinValue = new Irradiation(double.MinValue, BaseUnit); - QuantityType = QuantityType.Irradiation; - Units = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); - Zero = new Irradiation(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Irradiation, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Irradiation() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Irradiation(double value, IrradiationUnit unit) - { - if (unit == IrradiationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. - /// - public static IrradiationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Irradiation - /// - public static Irradiation MaxValue { get; } - - /// - /// Represents the smallest possible value of Irradiation - /// - public static Irradiation MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Irradiation quantity. - /// - public static IrradiationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. - /// - public static Irradiation Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Irradiation.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Irradiation.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerSquareCentimeter => As(IrradiationUnit.JoulePerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerSquareMillimeter => As(IrradiationUnit.JoulePerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerSquareMeter => As(IrradiationUnit.KilojoulePerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillijoulesPerSquareCentimeter => As(IrradiationUnit.MillijoulePerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(IrradiationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromJoulesPerSquareCentimeter(double joulespersquarecentimeter) - { - double value = (double) joulespersquarecentimeter; - return new Irradiation(value, IrradiationUnit.JoulePerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromJoulesPerSquareMeter(double joulespersquaremeter) - { - double value = (double) joulespersquaremeter; - return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromJoulesPerSquareMillimeter(double joulespersquaremillimeter) - { - double value = (double) joulespersquaremillimeter; - return new Irradiation(value, IrradiationUnit.JoulePerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromKilojoulesPerSquareMeter(double kilojoulespersquaremeter) - { - double value = (double) kilojoulespersquaremeter; - return new Irradiation(value, IrradiationUnit.KilojoulePerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromKilowattHoursPerSquareMeter(double kilowatthourspersquaremeter) - { - double value = (double) kilowatthourspersquaremeter; - return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromMillijoulesPerSquareCentimeter(double millijoulespersquarecentimeter) - { - double value = (double) millijoulespersquarecentimeter; - return new Irradiation(value, IrradiationUnit.MillijoulePerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Irradiation FromWattHoursPerSquareMeter(double watthourspersquaremeter) - { - double value = (double) watthourspersquaremeter; - return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Irradiation unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Irradiation From(double value, IrradiationUnit fromUnit) - { - return new Irradiation((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Irradiation Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Irradiation Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Irradiation result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Irradiation result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static IrradiationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out IrradiationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out IrradiationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Irradiation objIrradiation)) throw new ArgumentException("Expected type Irradiation.", nameof(obj)); - - return CompareTo(objIrradiation); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Irradiation other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Irradiation objIrradiation)) - return false; - - return Equals(objIrradiation); - } - - public bool Equals(Irradiation other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Irradiation within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Irradiation other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiation. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((IrradiationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradiationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Irradiation to another Irradiation with the unit representation . - /// - /// A Irradiation with the specified unit. - public Irradiation ToUnit(IrradiationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Irradiation(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case IrradiationUnit.JoulePerSquareCentimeter: return _value * 1e4; - case IrradiationUnit.JoulePerSquareMeter: return _value; - case IrradiationUnit.JoulePerSquareMillimeter: return _value * 1e6; - case IrradiationUnit.KilojoulePerSquareMeter: return (_value) * 1e3d; - case IrradiationUnit.KilowattHourPerSquareMeter: return (_value * 3600d) * 1e3d; - case IrradiationUnit.MillijoulePerSquareCentimeter: return (_value * 1e4) * 1e-3d; - case IrradiationUnit.WattHourPerSquareMeter: return _value * 3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(IrradiationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case IrradiationUnit.JoulePerSquareCentimeter: return baseUnitValue / 1e4; - case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; - case IrradiationUnit.JoulePerSquareMillimeter: return baseUnitValue / 1e6; - case IrradiationUnit.KilojoulePerSquareMeter: return (baseUnitValue) / 1e3d; - case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue / 3600d) / 1e3d; - case IrradiationUnit.MillijoulePerSquareCentimeter: return (baseUnitValue / 1e4) / 1e-3d; - case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue / 3600d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Jerk.g.cs deleted file mode 100644 index 97a8296c31..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Jerk.g.cs +++ /dev/null @@ -1,794 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Jerk or Jolt, in physics, is the rate at which the acceleration of an object changes over time. The SI unit for jerk is the Meter per second cubed (m/s³). Jerks are vector quantities (they have magnitude and direction) and add according to the parallelogram law. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Jerk : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly JerkUnit? _unit; - - static Jerk() - { - BaseDimensions = new BaseDimensions(1, 0, -3, 0, 0, 0, 0); - BaseUnit = JerkUnit.MeterPerSecondCubed; - MaxValue = new Jerk(double.MaxValue, BaseUnit); - MinValue = new Jerk(double.MinValue, BaseUnit); - QuantityType = QuantityType.Jerk; - Units = Enum.GetValues(typeof(JerkUnit)).Cast().Except(new JerkUnit[]{ JerkUnit.Undefined }).ToArray(); - Zero = new Jerk(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Jerk, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit MeterPerSecondCubed. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Jerk() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Jerk(double value, JerkUnit unit) - { - if (unit == JerkUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Jerk, which is MeterPerSecondCubed. All conversions go via this value. - /// - public static JerkUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Jerk - /// - public static Jerk MaxValue { get; } - - /// - /// Represents the smallest possible value of Jerk - /// - public static Jerk MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Jerk quantity. - /// - public static JerkUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondCubed. - /// - public static Jerk Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public JerkUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Jerk.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Jerk.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersPerSecondCubed => As(JerkUnit.CentimeterPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimetersPerSecondCubed => As(JerkUnit.DecimeterPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetPerSecondCubed => As(JerkUnit.FootPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesPerSecondCubed => As(JerkUnit.InchPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double KilometersPerSecondCubed => As(JerkUnit.KilometerPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersPerSecondCubed => As(JerkUnit.MeterPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrometersPerSecondCubed => As(JerkUnit.MicrometerPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersPerSecondCubed => As(JerkUnit.MillimeterPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double MillistandardGravitiesPerSecond => As(JerkUnit.MillistandardGravitiesPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanometersPerSecondCubed => As(JerkUnit.NanometerPerSecondCubed); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardGravitiesPerSecond => As(JerkUnit.StandardGravitiesPerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(JerkUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(JerkUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromCentimetersPerSecondCubed(double centimeterspersecondcubed) - { - double value = (double) centimeterspersecondcubed; - return new Jerk(value, JerkUnit.CentimeterPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromDecimetersPerSecondCubed(double decimeterspersecondcubed) - { - double value = (double) decimeterspersecondcubed; - return new Jerk(value, JerkUnit.DecimeterPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromFeetPerSecondCubed(double feetpersecondcubed) - { - double value = (double) feetpersecondcubed; - return new Jerk(value, JerkUnit.FootPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromInchesPerSecondCubed(double inchespersecondcubed) - { - double value = (double) inchespersecondcubed; - return new Jerk(value, JerkUnit.InchPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromKilometersPerSecondCubed(double kilometerspersecondcubed) - { - double value = (double) kilometerspersecondcubed; - return new Jerk(value, JerkUnit.KilometerPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromMetersPerSecondCubed(double meterspersecondcubed) - { - double value = (double) meterspersecondcubed; - return new Jerk(value, JerkUnit.MeterPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromMicrometersPerSecondCubed(double micrometerspersecondcubed) - { - double value = (double) micrometerspersecondcubed; - return new Jerk(value, JerkUnit.MicrometerPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromMillimetersPerSecondCubed(double millimeterspersecondcubed) - { - double value = (double) millimeterspersecondcubed; - return new Jerk(value, JerkUnit.MillimeterPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromMillistandardGravitiesPerSecond(double millistandardgravitiespersecond) - { - double value = (double) millistandardgravitiespersecond; - return new Jerk(value, JerkUnit.MillistandardGravitiesPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromNanometersPerSecondCubed(double nanometerspersecondcubed) - { - double value = (double) nanometerspersecondcubed; - return new Jerk(value, JerkUnit.NanometerPerSecondCubed); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Jerk FromStandardGravitiesPerSecond(double standardgravitiespersecond) - { - double value = (double) standardgravitiespersecond; - return new Jerk(value, JerkUnit.StandardGravitiesPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Jerk unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Jerk From(double value, JerkUnit fromUnit) - { - return new Jerk((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Jerk Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Jerk Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Jerk result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Jerk result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static JerkUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static JerkUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out JerkUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out JerkUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Jerk objJerk)) throw new ArgumentException("Expected type Jerk.", nameof(obj)); - - return CompareTo(objJerk); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Jerk other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Jerk objJerk)) - return false; - - return Equals(objJerk); - } - - public bool Equals(Jerk other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Jerk within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Jerk. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((JerkUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(JerkUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Jerk to another Jerk with the unit representation . - /// - /// A Jerk with the specified unit. - public Jerk ToUnit(JerkUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Jerk(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case JerkUnit.CentimeterPerSecondCubed: return (_value) * 1e-2d; - case JerkUnit.DecimeterPerSecondCubed: return (_value) * 1e-1d; - case JerkUnit.FootPerSecondCubed: return _value * 0.304800; - case JerkUnit.InchPerSecondCubed: return _value * 0.0254; - case JerkUnit.KilometerPerSecondCubed: return (_value) * 1e3d; - case JerkUnit.MeterPerSecondCubed: return _value; - case JerkUnit.MicrometerPerSecondCubed: return (_value) * 1e-6d; - case JerkUnit.MillimeterPerSecondCubed: return (_value) * 1e-3d; - case JerkUnit.MillistandardGravitiesPerSecond: return (_value * 9.80665) * 1e-3d; - case JerkUnit.NanometerPerSecondCubed: return (_value) * 1e-9d; - case JerkUnit.StandardGravitiesPerSecond: return _value * 9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(JerkUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case JerkUnit.CentimeterPerSecondCubed: return (baseUnitValue) / 1e-2d; - case JerkUnit.DecimeterPerSecondCubed: return (baseUnitValue) / 1e-1d; - case JerkUnit.FootPerSecondCubed: return baseUnitValue / 0.304800; - case JerkUnit.InchPerSecondCubed: return baseUnitValue / 0.0254; - case JerkUnit.KilometerPerSecondCubed: return (baseUnitValue) / 1e3d; - case JerkUnit.MeterPerSecondCubed: return baseUnitValue; - case JerkUnit.MicrometerPerSecondCubed: return (baseUnitValue) / 1e-6d; - case JerkUnit.MillimeterPerSecondCubed: return (baseUnitValue) / 1e-3d; - case JerkUnit.MillistandardGravitiesPerSecond: return (baseUnitValue / 9.80665) / 1e-3d; - case JerkUnit.NanometerPerSecondCubed: return (baseUnitValue) / 1e-9d; - case JerkUnit.StandardGravitiesPerSecond: return baseUnitValue / 9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.g.cs deleted file mode 100644 index 931579bc8f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ /dev/null @@ -1,756 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress. - /// - /// - /// http://en.wikipedia.org/wiki/Viscosity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class KinematicViscosity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly KinematicViscosityUnit? _unit; - - static KinematicViscosity() - { - BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); - BaseUnit = KinematicViscosityUnit.SquareMeterPerSecond; - MaxValue = new KinematicViscosity(double.MaxValue, BaseUnit); - MinValue = new KinematicViscosity(double.MinValue, BaseUnit); - QuantityType = QuantityType.KinematicViscosity; - Units = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); - Zero = new KinematicViscosity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.KinematicViscosity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit SquareMeterPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public KinematicViscosity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private KinematicViscosity(double value, KinematicViscosityUnit unit) - { - if (unit == KinematicViscosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. - /// - public static KinematicViscosityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of KinematicViscosity - /// - public static KinematicViscosity MaxValue { get; } - - /// - /// Represents the smallest possible value of KinematicViscosity - /// - public static KinematicViscosity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the KinematicViscosity quantity. - /// - public static KinematicViscosityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. - /// - public static KinematicViscosity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => KinematicViscosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Centistokes => As(KinematicViscosityUnit.Centistokes); - - /// - /// Gets a value of this quantity converted into - /// - public double Decistokes => As(KinematicViscosityUnit.Decistokes); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); - - /// - /// Gets a value of this quantity converted into - /// - public double Microstokes => As(KinematicViscosityUnit.Microstokes); - - /// - /// Gets a value of this quantity converted into - /// - public double Millistokes => As(KinematicViscosityUnit.Millistokes); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareFeetPerSecond => As(KinematicViscosityUnit.SquareFootPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Stokes => As(KinematicViscosityUnit.Stokes); - - #endregion - - #region Static Methods - - 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[]{"Ст"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(KinematicViscosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromCentistokes(double centistokes) - { - double value = (double) centistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromDecistokes(double decistokes) - { - double value = (double) decistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromKilostokes(double kilostokes) - { - double value = (double) kilostokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromMicrostokes(double microstokes) - { - double value = (double) microstokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromMillistokes(double millistokes) - { - double value = (double) millistokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromNanostokes(double nanostokes) - { - double value = (double) nanostokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromSquareFeetPerSecond(double squarefeetpersecond) - { - double value = (double) squarefeetpersecond; - return new KinematicViscosity(value, KinematicViscosityUnit.SquareFootPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromSquareMetersPerSecond(double squaremeterspersecond) - { - double value = (double) squaremeterspersecond; - return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static KinematicViscosity FromStokes(double stokes) - { - double value = (double) stokes; - return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// KinematicViscosity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static KinematicViscosity From(double value, KinematicViscosityUnit fromUnit) - { - return new KinematicViscosity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static KinematicViscosity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static KinematicViscosity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out KinematicViscosity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out KinematicViscosity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static KinematicViscosityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out KinematicViscosityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is KinematicViscosity objKinematicViscosity)) throw new ArgumentException("Expected type KinematicViscosity.", nameof(obj)); - - return CompareTo(objKinematicViscosity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(KinematicViscosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is KinematicViscosity objKinematicViscosity)) - return false; - - return Equals(objKinematicViscosity); - } - - public bool Equals(KinematicViscosity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another KinematicViscosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(KinematicViscosity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current KinematicViscosity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((KinematicViscosityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(KinematicViscosityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation . - /// - /// A KinematicViscosity with the specified unit. - public KinematicViscosity ToUnit(KinematicViscosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new KinematicViscosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case KinematicViscosityUnit.Centistokes: return (_value / 1e4) * 1e-2d; - case KinematicViscosityUnit.Decistokes: return (_value / 1e4) * 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (_value / 1e4) * 1e3d; - case KinematicViscosityUnit.Microstokes: return (_value / 1e4) * 1e-6d; - case KinematicViscosityUnit.Millistokes: return (_value / 1e4) * 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (_value / 1e4) * 1e-9d; - case KinematicViscosityUnit.SquareFootPerSecond: return _value / 10.7639; - case KinematicViscosityUnit.SquareMeterPerSecond: return _value; - case KinematicViscosityUnit.Stokes: return _value / 1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(KinematicViscosityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case KinematicViscosityUnit.Centistokes: return (baseUnitValue * 1e4) / 1e-2d; - case KinematicViscosityUnit.Decistokes: return (baseUnitValue * 1e4) / 1e-1d; - case KinematicViscosityUnit.Kilostokes: return (baseUnitValue * 1e4) / 1e3d; - case KinematicViscosityUnit.Microstokes: return (baseUnitValue * 1e4) / 1e-6d; - case KinematicViscosityUnit.Millistokes: return (baseUnitValue * 1e4) / 1e-3d; - case KinematicViscosityUnit.Nanostokes: return (baseUnitValue * 1e4) / 1e-9d; - case KinematicViscosityUnit.SquareFootPerSecond: return baseUnitValue * 10.7639; - case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; - case KinematicViscosityUnit.Stokes: return baseUnitValue * 1e4; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.g.cs deleted file mode 100644 index 02bfedefc6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LapseRate.g.cs +++ /dev/null @@ -1,594 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude. - /// - [Obsolete("Use TemperatureGradient instead.")] - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class LapseRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LapseRateUnit? _unit; - - static LapseRate() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); - BaseUnit = LapseRateUnit.DegreeCelsiusPerKilometer; - MaxValue = new LapseRate(double.MaxValue, BaseUnit); - MinValue = new LapseRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.LapseRate; - Units = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); - Zero = new LapseRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.LapseRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public LapseRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private LapseRate(double value, LapseRateUnit unit) - { - if (unit == LapseRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of LapseRate, which is DegreeCelsiusPerKilometer. All conversions go via this value. - /// - public static LapseRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of LapseRate - /// - public static LapseRate MaxValue { get; } - - /// - /// Represents the smallest possible value of LapseRate - /// - public static LapseRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the LapseRate quantity. - /// - public static LapseRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerKilometer. - /// - public static LapseRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => LapseRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LapseRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(LapseRateUnit.DegreeCelsiusPerKilometer, new CultureInfo("en-US"), false, true, new string[]{"∆°C/km"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LapseRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LapseRate FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) - { - double value = (double) degreescelciusperkilometer; - return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LapseRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LapseRate From(double value, LapseRateUnit fromUnit) - { - return new LapseRate((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LapseRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LapseRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LapseRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out LapseRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LapseRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LapseRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LapseRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LapseRate objLapseRate)) throw new ArgumentException("Expected type LapseRate.", nameof(obj)); - - return CompareTo(objLapseRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(LapseRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is LapseRate objLapseRate)) - return false; - - return Equals(objLapseRate); - } - - public bool Equals(LapseRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LapseRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LapseRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LapseRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LapseRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LapseRate to another LapseRate with the unit representation . - /// - /// A LapseRate with the specified unit. - public LapseRate ToUnit(LapseRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LapseRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LapseRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.g.cs deleted file mode 100644 index e940a1507f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Length.g.cs +++ /dev/null @@ -1,1290 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Length : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LengthUnit? _unit; - - static Length() - { - BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - BaseUnit = LengthUnit.Meter; - MaxValue = new Length(double.MaxValue, BaseUnit); - MinValue = new Length(double.MinValue, BaseUnit); - QuantityType = QuantityType.Length; - Units = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); - Zero = new Length(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Length, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Meter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Length() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Length(double value, LengthUnit unit) - { - if (unit == LengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Length, which is Meter. All conversions go via this value. - /// - public static LengthUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Length - /// - public static Length MaxValue { get; } - - /// - /// Represents the smallest possible value of Length - /// - public static Length MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Length quantity. - /// - public static LengthUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Meter. - /// - public static Length Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Length.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Length.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Angstroms => As(LengthUnit.Angstrom); - - /// - /// Gets a value of this quantity converted into - /// - public double AstronomicalUnits => As(LengthUnit.AstronomicalUnit); - - /// - /// Gets a value of this quantity converted into - /// - public double Centimeters => As(LengthUnit.Centimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Chains => As(LengthUnit.Chain); - - /// - /// Gets a value of this quantity converted into - /// - public double DataMiles => As(LengthUnit.DataMile); - - /// - /// Gets a value of this quantity converted into - /// - public double Decameters => As(LengthUnit.Decameter); - - /// - /// Gets a value of this quantity converted into - /// - public double Decimeters => As(LengthUnit.Decimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DtpPicas => As(LengthUnit.DtpPica); - - /// - /// Gets a value of this quantity converted into - /// - public double DtpPoints => As(LengthUnit.DtpPoint); - - /// - /// Gets a value of this quantity converted into - /// - public double Fathoms => As(LengthUnit.Fathom); - - /// - /// Gets a value of this quantity converted into - /// - public double Feet => As(LengthUnit.Foot); - - /// - /// Gets a value of this quantity converted into - /// - public double Hands => As(LengthUnit.Hand); - - /// - /// Gets a value of this quantity converted into - /// - public double Hectometers => As(LengthUnit.Hectometer); - - /// - /// Gets a value of this quantity converted into - /// - public double Inches => As(LengthUnit.Inch); - - /// - /// Gets a value of this quantity converted into - /// - public double KilolightYears => As(LengthUnit.KilolightYear); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilometers => As(LengthUnit.Kilometer); - - /// - /// Gets a value of this quantity converted into - /// - public double Kiloparsecs => As(LengthUnit.Kiloparsec); - - /// - /// Gets a value of this quantity converted into - /// - public double LightYears => As(LengthUnit.LightYear); - - /// - /// Gets a value of this quantity converted into - /// - public double MegalightYears => As(LengthUnit.MegalightYear); - - /// - /// Gets a value of this quantity converted into - /// - public double Megaparsecs => As(LengthUnit.Megaparsec); - - /// - /// Gets a value of this quantity converted into - /// - public double Meters => As(LengthUnit.Meter); - - /// - /// Gets a value of this quantity converted into - /// - public double Microinches => As(LengthUnit.Microinch); - - /// - /// Gets a value of this quantity converted into - /// - public double Micrometers => As(LengthUnit.Micrometer); - - /// - /// Gets a value of this quantity converted into - /// - public double Mils => As(LengthUnit.Mil); - - /// - /// Gets a value of this quantity converted into - /// - public double Miles => As(LengthUnit.Mile); - - /// - /// Gets a value of this quantity converted into - /// - public double Millimeters => As(LengthUnit.Millimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanometers => As(LengthUnit.Nanometer); - - /// - /// Gets a value of this quantity converted into - /// - public double NauticalMiles => As(LengthUnit.NauticalMile); - - /// - /// Gets a value of this quantity converted into - /// - public double Parsecs => As(LengthUnit.Parsec); - - /// - /// Gets a value of this quantity converted into - /// - public double PrinterPicas => As(LengthUnit.PrinterPica); - - /// - /// Gets a value of this quantity converted into - /// - public double PrinterPoints => As(LengthUnit.PrinterPoint); - - /// - /// Gets a value of this quantity converted into - /// - public double Shackles => As(LengthUnit.Shackle); - - /// - /// Gets a value of this quantity converted into - /// - public double SolarRadiuses => As(LengthUnit.SolarRadius); - - /// - /// Gets a value of this quantity converted into - /// - public double Twips => As(LengthUnit.Twip); - - /// - /// Gets a value of this quantity converted into - /// - public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double Yards => As(LengthUnit.Yard); - - #endregion - - #region Static Methods - - 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[]{"码"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LengthUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromAngstroms(double angstroms) - { - double value = (double) angstroms; - return new Length(value, LengthUnit.Angstrom); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromAstronomicalUnits(double astronomicalunits) - { - double value = (double) astronomicalunits; - return new Length(value, LengthUnit.AstronomicalUnit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromCentimeters(double centimeters) - { - double value = (double) centimeters; - return new Length(value, LengthUnit.Centimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromChains(double chains) - { - double value = (double) chains; - return new Length(value, LengthUnit.Chain); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDataMiles(double datamiles) - { - double value = (double) datamiles; - return new Length(value, LengthUnit.DataMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDecameters(double decameters) - { - double value = (double) decameters; - return new Length(value, LengthUnit.Decameter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDecimeters(double decimeters) - { - double value = (double) decimeters; - return new Length(value, LengthUnit.Decimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDtpPicas(double dtppicas) - { - double value = (double) dtppicas; - return new Length(value, LengthUnit.DtpPica); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromDtpPoints(double dtppoints) - { - double value = (double) dtppoints; - return new Length(value, LengthUnit.DtpPoint); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromFathoms(double fathoms) - { - double value = (double) fathoms; - return new Length(value, LengthUnit.Fathom); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromFeet(double feet) - { - double value = (double) feet; - return new Length(value, LengthUnit.Foot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromHands(double hands) - { - double value = (double) hands; - return new Length(value, LengthUnit.Hand); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromHectometers(double hectometers) - { - double value = (double) hectometers; - return new Length(value, LengthUnit.Hectometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromInches(double inches) - { - double value = (double) inches; - return new Length(value, LengthUnit.Inch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromKilolightYears(double kilolightyears) - { - double value = (double) kilolightyears; - return new Length(value, LengthUnit.KilolightYear); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromKilometers(double kilometers) - { - double value = (double) kilometers; - return new Length(value, LengthUnit.Kilometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromKiloparsecs(double kiloparsecs) - { - double value = (double) kiloparsecs; - return new Length(value, LengthUnit.Kiloparsec); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromLightYears(double lightyears) - { - double value = (double) lightyears; - return new Length(value, LengthUnit.LightYear); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMegalightYears(double megalightyears) - { - double value = (double) megalightyears; - return new Length(value, LengthUnit.MegalightYear); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMegaparsecs(double megaparsecs) - { - double value = (double) megaparsecs; - return new Length(value, LengthUnit.Megaparsec); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMeters(double meters) - { - double value = (double) meters; - return new Length(value, LengthUnit.Meter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMicroinches(double microinches) - { - double value = (double) microinches; - return new Length(value, LengthUnit.Microinch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMicrometers(double micrometers) - { - double value = (double) micrometers; - return new Length(value, LengthUnit.Micrometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMils(double mils) - { - double value = (double) mils; - return new Length(value, LengthUnit.Mil); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMiles(double miles) - { - double value = (double) miles; - return new Length(value, LengthUnit.Mile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromMillimeters(double millimeters) - { - double value = (double) millimeters; - return new Length(value, LengthUnit.Millimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromNanometers(double nanometers) - { - double value = (double) nanometers; - return new Length(value, LengthUnit.Nanometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromNauticalMiles(double nauticalmiles) - { - double value = (double) nauticalmiles; - return new Length(value, LengthUnit.NauticalMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromParsecs(double parsecs) - { - double value = (double) parsecs; - return new Length(value, LengthUnit.Parsec); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromPrinterPicas(double printerpicas) - { - double value = (double) printerpicas; - return new Length(value, LengthUnit.PrinterPica); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromPrinterPoints(double printerpoints) - { - double value = (double) printerpoints; - return new Length(value, LengthUnit.PrinterPoint); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromShackles(double shackles) - { - double value = (double) shackles; - return new Length(value, LengthUnit.Shackle); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromSolarRadiuses(double solarradiuses) - { - double value = (double) solarradiuses; - return new Length(value, LengthUnit.SolarRadius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromTwips(double twips) - { - double value = (double) twips; - return new Length(value, LengthUnit.Twip); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromUsSurveyFeet(double ussurveyfeet) - { - double value = (double) ussurveyfeet; - return new Length(value, LengthUnit.UsSurveyFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Length FromYards(double yards) - { - double value = (double) yards; - return new Length(value, LengthUnit.Yard); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Length unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Length From(double value, LengthUnit fromUnit) - { - return new Length((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Length Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Length Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Length result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Length result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LengthUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LengthUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LengthUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Length objLength)) throw new ArgumentException("Expected type Length.", nameof(obj)); - - return CompareTo(objLength); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Length other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Length objLength)) - return false; - - return Equals(objLength); - } - - public bool Equals(Length other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Length within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Length other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Length. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LengthUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LengthUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Length to another Length with the unit representation . - /// - /// A Length with the specified unit. - public Length ToUnit(LengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Length(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LengthUnit.Angstrom: return _value * 1e-10; - case LengthUnit.AstronomicalUnit: return _value * 1.4959787070e11; - case LengthUnit.Centimeter: return (_value) * 1e-2d; - case LengthUnit.Chain: return _value * 20.1168; - case LengthUnit.DataMile: return _value * 1828.8; - case LengthUnit.Decameter: return (_value) * 1e1d; - case LengthUnit.Decimeter: return (_value) * 1e-1d; - case LengthUnit.DtpPica: return _value / 236.220472441; - case LengthUnit.DtpPoint: return (_value / 72) * 2.54e-2; - case LengthUnit.Fathom: return _value * 1.8288; - case LengthUnit.Foot: return _value * 0.3048; - case LengthUnit.Hand: return _value * 1.016e-1; - case LengthUnit.Hectometer: return (_value) * 1e2d; - case LengthUnit.Inch: return _value * 2.54e-2; - case LengthUnit.KilolightYear: return (_value * 9.46073047258e15) * 1e3d; - case LengthUnit.Kilometer: return (_value) * 1e3d; - case LengthUnit.Kiloparsec: return (_value * 3.08567758128e16) * 1e3d; - case LengthUnit.LightYear: return _value * 9.46073047258e15; - case LengthUnit.MegalightYear: return (_value * 9.46073047258e15) * 1e6d; - case LengthUnit.Megaparsec: return (_value * 3.08567758128e16) * 1e6d; - case LengthUnit.Meter: return _value; - case LengthUnit.Microinch: return _value * 2.54e-8; - case LengthUnit.Micrometer: return (_value) * 1e-6d; - case LengthUnit.Mil: return _value * 2.54e-5; - case LengthUnit.Mile: return _value * 1609.34; - case LengthUnit.Millimeter: return (_value) * 1e-3d; - case LengthUnit.Nanometer: return (_value) * 1e-9d; - case LengthUnit.NauticalMile: return _value * 1852; - case LengthUnit.Parsec: return _value * 3.08567758128e16; - case LengthUnit.PrinterPica: return _value / 237.106301584; - case LengthUnit.PrinterPoint: return (_value / 72.27) * 2.54e-2; - case LengthUnit.Shackle: return _value * 27.432; - case LengthUnit.SolarRadius: return _value * 6.95510000E+08; - case LengthUnit.Twip: return _value / 56692.913385826; - case LengthUnit.UsSurveyFoot: return _value * 1200 / 3937; - case LengthUnit.Yard: return _value * 0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LengthUnit.Angstrom: return baseUnitValue / 1e-10; - case LengthUnit.AstronomicalUnit: return baseUnitValue / 1.4959787070e11; - case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; - case LengthUnit.Chain: return baseUnitValue / 20.1168; - case LengthUnit.DataMile: return baseUnitValue / 1828.8; - case LengthUnit.Decameter: return (baseUnitValue) / 1e1d; - case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; - case LengthUnit.DtpPica: return baseUnitValue * 236.220472441; - case LengthUnit.DtpPoint: return (baseUnitValue / 2.54e-2) * 72; - case LengthUnit.Fathom: return baseUnitValue / 1.8288; - case LengthUnit.Foot: return baseUnitValue / 0.3048; - case LengthUnit.Hand: return baseUnitValue / 1.016e-1; - case LengthUnit.Hectometer: return (baseUnitValue) / 1e2d; - case LengthUnit.Inch: return baseUnitValue / 2.54e-2; - case LengthUnit.KilolightYear: return (baseUnitValue / 9.46073047258e15) / 1e3d; - case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; - case LengthUnit.Kiloparsec: return (baseUnitValue / 3.08567758128e16) / 1e3d; - case LengthUnit.LightYear: return baseUnitValue / 9.46073047258e15; - case LengthUnit.MegalightYear: return (baseUnitValue / 9.46073047258e15) / 1e6d; - case LengthUnit.Megaparsec: return (baseUnitValue / 3.08567758128e16) / 1e6d; - case LengthUnit.Meter: return baseUnitValue; - case LengthUnit.Microinch: return baseUnitValue / 2.54e-8; - case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; - case LengthUnit.Mil: return baseUnitValue / 2.54e-5; - case LengthUnit.Mile: return baseUnitValue / 1609.34; - case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; - case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; - case LengthUnit.NauticalMile: return baseUnitValue / 1852; - case LengthUnit.Parsec: return baseUnitValue / 3.08567758128e16; - case LengthUnit.PrinterPica: return baseUnitValue * 237.106301584; - case LengthUnit.PrinterPoint: return (baseUnitValue / 2.54e-2) * 72.27; - case LengthUnit.Shackle: return baseUnitValue / 27.432; - case LengthUnit.SolarRadius: return baseUnitValue / 6.95510000E+08; - case LengthUnit.Twip: return baseUnitValue * 56692.913385826; - case LengthUnit.UsSurveyFoot: return baseUnitValue * 3937 / 1200; - case LengthUnit.Yard: return baseUnitValue / 0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.g.cs deleted file mode 100644 index 043a2765fe..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.g.cs +++ /dev/null @@ -1,612 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Level : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LevelUnit? _unit; - - static Level() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = LevelUnit.Decibel; - MaxValue = new Level(double.MaxValue, BaseUnit); - MinValue = new Level(double.MinValue, BaseUnit); - QuantityType = QuantityType.Level; - Units = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); - Zero = new Level(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Level, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Decibel. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Level() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Level(double value, LevelUnit unit) - { - if (unit == LevelUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Level, which is Decibel. All conversions go via this value. - /// - public static LevelUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Level - /// - public static Level MaxValue { get; } - - /// - /// Represents the smallest possible value of Level - /// - public static Level MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Level quantity. - /// - public static LevelUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. - /// - public static Level Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Level.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Level.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Decibels => As(LevelUnit.Decibel); - - /// - /// Gets a value of this quantity converted into - /// - public double Nepers => As(LevelUnit.Neper); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LevelUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LevelUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Level FromDecibels(double decibels) - { - double value = (double) decibels; - return new Level(value, LevelUnit.Decibel); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Level FromNepers(double nepers) - { - double value = (double) nepers; - return new Level(value, LevelUnit.Neper); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Level unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Level From(double value, LevelUnit fromUnit) - { - return new Level((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Level Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Level Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Level result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Level result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LevelUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LevelUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LevelUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Level objLevel)) throw new ArgumentException("Expected type Level.", nameof(obj)); - - return CompareTo(objLevel); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Level other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Level objLevel)) - return false; - - return Equals(objLevel); - } - - public bool Equals(Level other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Level within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Level other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Level. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LevelUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LevelUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Level to another Level with the unit representation . - /// - /// A Level with the specified unit. - public Level ToUnit(LevelUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Level(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LevelUnit.Decibel: return _value; - case LevelUnit.Neper: return (1 / 0.115129254) * _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LevelUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LevelUnit.Decibel: return baseUnitValue; - case LevelUnit.Neper: return 0.115129254 * baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.g.cs deleted file mode 100644 index 1ab6387a2f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearDensity.g.cs +++ /dev/null @@ -1,843 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension. - /// - /// - /// http://en.wikipedia.org/wiki/Linear_density - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class LinearDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LinearDensityUnit? _unit; - - static LinearDensity() - { - BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); - BaseUnit = LinearDensityUnit.KilogramPerMeter; - MaxValue = new LinearDensity(double.MaxValue, BaseUnit); - MinValue = new LinearDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.LinearDensity; - Units = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); - Zero = new LinearDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.LinearDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public LinearDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private LinearDensity(double value, LinearDensityUnit unit) - { - if (unit == LinearDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. - /// - public static LinearDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of LinearDensity - /// - public static LinearDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of LinearDensity - /// - public static LinearDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the LinearDensity quantity. - /// - public static LinearDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. - /// - public static LinearDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => LinearDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LinearDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCentimeter => As(LinearDensityUnit.GramPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerMillimeter => As(LinearDensityUnit.GramPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCentimeter => As(LinearDensityUnit.KilogramPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerMillimeter => As(LinearDensityUnit.KilogramPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerCentimeter => As(LinearDensityUnit.MicrogramPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerMeter => As(LinearDensityUnit.MicrogramPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerMillimeter => As(LinearDensityUnit.MicrogramPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerCentimeter => As(LinearDensityUnit.MilligramPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerMeter => As(LinearDensityUnit.MilligramPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerMillimeter => As(LinearDensityUnit.MilligramPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerInch => As(LinearDensityUnit.PoundPerInch); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LinearDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromGramsPerCentimeter(double gramspercentimeter) - { - double value = (double) gramspercentimeter; - return new LinearDensity(value, LinearDensityUnit.GramPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromGramsPerMeter(double gramspermeter) - { - double value = (double) gramspermeter; - return new LinearDensity(value, LinearDensityUnit.GramPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromGramsPerMillimeter(double gramspermillimeter) - { - double value = (double) gramspermillimeter; - return new LinearDensity(value, LinearDensityUnit.GramPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromKilogramsPerCentimeter(double kilogramspercentimeter) - { - double value = (double) kilogramspercentimeter; - return new LinearDensity(value, LinearDensityUnit.KilogramPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromKilogramsPerMeter(double kilogramspermeter) - { - double value = (double) kilogramspermeter; - return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromKilogramsPerMillimeter(double kilogramspermillimeter) - { - double value = (double) kilogramspermillimeter; - return new LinearDensity(value, LinearDensityUnit.KilogramPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromMicrogramsPerCentimeter(double microgramspercentimeter) - { - double value = (double) microgramspercentimeter; - return new LinearDensity(value, LinearDensityUnit.MicrogramPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromMicrogramsPerMeter(double microgramspermeter) - { - double value = (double) microgramspermeter; - return new LinearDensity(value, LinearDensityUnit.MicrogramPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromMicrogramsPerMillimeter(double microgramspermillimeter) - { - double value = (double) microgramspermillimeter; - return new LinearDensity(value, LinearDensityUnit.MicrogramPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromMilligramsPerCentimeter(double milligramspercentimeter) - { - double value = (double) milligramspercentimeter; - return new LinearDensity(value, LinearDensityUnit.MilligramPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromMilligramsPerMeter(double milligramspermeter) - { - double value = (double) milligramspermeter; - return new LinearDensity(value, LinearDensityUnit.MilligramPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromMilligramsPerMillimeter(double milligramspermillimeter) - { - double value = (double) milligramspermillimeter; - return new LinearDensity(value, LinearDensityUnit.MilligramPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromPoundsPerFoot(double poundsperfoot) - { - double value = (double) poundsperfoot; - return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearDensity FromPoundsPerInch(double poundsperinch) - { - double value = (double) poundsperinch; - return new LinearDensity(value, LinearDensityUnit.PoundPerInch); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LinearDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LinearDensity From(double value, LinearDensityUnit fromUnit) - { - return new LinearDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LinearDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LinearDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LinearDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out LinearDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LinearDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LinearDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LinearDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LinearDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LinearDensity objLinearDensity)) throw new ArgumentException("Expected type LinearDensity.", nameof(obj)); - - return CompareTo(objLinearDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(LinearDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is LinearDensity objLinearDensity)) - return false; - - return Equals(objLinearDensity); - } - - public bool Equals(LinearDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LinearDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LinearDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LinearDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LinearDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LinearDensity to another LinearDensity with the unit representation . - /// - /// A LinearDensity with the specified unit. - public LinearDensity ToUnit(LinearDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LinearDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LinearDensityUnit.GramPerCentimeter: return _value * 1e-1; - case LinearDensityUnit.GramPerMeter: return _value * 1e-3; - case LinearDensityUnit.GramPerMillimeter: return _value; - case LinearDensityUnit.KilogramPerCentimeter: return (_value * 1e-1) * 1e3d; - case LinearDensityUnit.KilogramPerMeter: return (_value * 1e-3) * 1e3d; - case LinearDensityUnit.KilogramPerMillimeter: return (_value) * 1e3d; - case LinearDensityUnit.MicrogramPerCentimeter: return (_value * 1e-1) * 1e-6d; - case LinearDensityUnit.MicrogramPerMeter: return (_value * 1e-3) * 1e-6d; - case LinearDensityUnit.MicrogramPerMillimeter: return (_value) * 1e-6d; - case LinearDensityUnit.MilligramPerCentimeter: return (_value * 1e-1) * 1e-3d; - case LinearDensityUnit.MilligramPerMeter: return (_value * 1e-3) * 1e-3d; - case LinearDensityUnit.MilligramPerMillimeter: return (_value) * 1e-3d; - case LinearDensityUnit.PoundPerFoot: return _value * 1.48816394; - case LinearDensityUnit.PoundPerInch: return _value / 5.5997415e-2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LinearDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LinearDensityUnit.GramPerCentimeter: return baseUnitValue / 1e-1; - case LinearDensityUnit.GramPerMeter: return baseUnitValue / 1e-3; - case LinearDensityUnit.GramPerMillimeter: return baseUnitValue; - case LinearDensityUnit.KilogramPerCentimeter: return (baseUnitValue / 1e-1) / 1e3d; - case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue / 1e-3) / 1e3d; - case LinearDensityUnit.KilogramPerMillimeter: return (baseUnitValue) / 1e3d; - case LinearDensityUnit.MicrogramPerCentimeter: return (baseUnitValue / 1e-1) / 1e-6d; - case LinearDensityUnit.MicrogramPerMeter: return (baseUnitValue / 1e-3) / 1e-6d; - case LinearDensityUnit.MicrogramPerMillimeter: return (baseUnitValue) / 1e-6d; - case LinearDensityUnit.MilligramPerCentimeter: return (baseUnitValue / 1e-1) / 1e-3d; - case LinearDensityUnit.MilligramPerMeter: return (baseUnitValue / 1e-3) / 1e-3d; - case LinearDensityUnit.MilligramPerMillimeter: return (baseUnitValue) / 1e-3d; - case LinearDensityUnit.PoundPerFoot: return baseUnitValue / 1.48816394; - case LinearDensityUnit.PoundPerInch: return baseUnitValue * 5.5997415e-2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearPowerDensity.g.cs deleted file mode 100644 index 6a3469536b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ /dev/null @@ -1,1052 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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. - /// - /// - /// http://en.wikipedia.org/wiki/Linear_density - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class LinearPowerDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LinearPowerDensityUnit? _unit; - - static LinearPowerDensity() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); - BaseUnit = LinearPowerDensityUnit.WattPerMeter; - MaxValue = new LinearPowerDensity(double.MaxValue, BaseUnit); - MinValue = new LinearPowerDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.LinearPowerDensity; - Units = Enum.GetValues(typeof(LinearPowerDensityUnit)).Cast().Except(new LinearPowerDensityUnit[]{ LinearPowerDensityUnit.Undefined }).ToArray(); - Zero = new LinearPowerDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.LinearPowerDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit WattPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public LinearPowerDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private LinearPowerDensity(double value, LinearPowerDensityUnit unit) - { - if (unit == LinearPowerDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of LinearPowerDensity, which is WattPerMeter. All conversions go via this value. - /// - public static LinearPowerDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of LinearPowerDensity - /// - public static LinearPowerDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of LinearPowerDensity - /// - public static LinearPowerDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the LinearPowerDensity quantity. - /// - public static LinearPowerDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeter. - /// - public static LinearPowerDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LinearPowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => LinearPowerDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LinearPowerDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerCentimeter => As(LinearPowerDensityUnit.GigawattPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerFoot => As(LinearPowerDensityUnit.GigawattPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerInch => As(LinearPowerDensityUnit.GigawattPerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerMeter => As(LinearPowerDensityUnit.GigawattPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerMillimeter => As(LinearPowerDensityUnit.GigawattPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerCentimeter => As(LinearPowerDensityUnit.KilowattPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerFoot => As(LinearPowerDensityUnit.KilowattPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerInch => As(LinearPowerDensityUnit.KilowattPerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerMeter => As(LinearPowerDensityUnit.KilowattPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerMillimeter => As(LinearPowerDensityUnit.KilowattPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerCentimeter => As(LinearPowerDensityUnit.MegawattPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerFoot => As(LinearPowerDensityUnit.MegawattPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerInch => As(LinearPowerDensityUnit.MegawattPerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerMeter => As(LinearPowerDensityUnit.MegawattPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerMillimeter => As(LinearPowerDensityUnit.MegawattPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerCentimeter => As(LinearPowerDensityUnit.MilliwattPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerFoot => As(LinearPowerDensityUnit.MilliwattPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerInch => As(LinearPowerDensityUnit.MilliwattPerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerMeter => As(LinearPowerDensityUnit.MilliwattPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerMillimeter => As(LinearPowerDensityUnit.MilliwattPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerCentimeter => As(LinearPowerDensityUnit.WattPerCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerFoot => As(LinearPowerDensityUnit.WattPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerInch => As(LinearPowerDensityUnit.WattPerInch); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerMeter => As(LinearPowerDensityUnit.WattPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerMillimeter => As(LinearPowerDensityUnit.WattPerMillimeter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LinearPowerDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LinearPowerDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromGigawattsPerCentimeter(double gigawattspercentimeter) - { - double value = (double) gigawattspercentimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromGigawattsPerFoot(double gigawattsperfoot) - { - double value = (double) gigawattsperfoot; - return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromGigawattsPerInch(double gigawattsperinch) - { - double value = (double) gigawattsperinch; - return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromGigawattsPerMeter(double gigawattspermeter) - { - double value = (double) gigawattspermeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromGigawattsPerMillimeter(double gigawattspermillimeter) - { - double value = (double) gigawattspermillimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromKilowattsPerCentimeter(double kilowattspercentimeter) - { - double value = (double) kilowattspercentimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromKilowattsPerFoot(double kilowattsperfoot) - { - double value = (double) kilowattsperfoot; - return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromKilowattsPerInch(double kilowattsperinch) - { - double value = (double) kilowattsperinch; - return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromKilowattsPerMeter(double kilowattspermeter) - { - double value = (double) kilowattspermeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromKilowattsPerMillimeter(double kilowattspermillimeter) - { - double value = (double) kilowattspermillimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMegawattsPerCentimeter(double megawattspercentimeter) - { - double value = (double) megawattspercentimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMegawattsPerFoot(double megawattsperfoot) - { - double value = (double) megawattsperfoot; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMegawattsPerInch(double megawattsperinch) - { - double value = (double) megawattsperinch; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMegawattsPerMeter(double megawattspermeter) - { - double value = (double) megawattspermeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMegawattsPerMillimeter(double megawattspermillimeter) - { - double value = (double) megawattspermillimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMilliwattsPerCentimeter(double milliwattspercentimeter) - { - double value = (double) milliwattspercentimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMilliwattsPerFoot(double milliwattsperfoot) - { - double value = (double) milliwattsperfoot; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMilliwattsPerInch(double milliwattsperinch) - { - double value = (double) milliwattsperinch; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMilliwattsPerMeter(double milliwattspermeter) - { - double value = (double) milliwattspermeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromMilliwattsPerMillimeter(double milliwattspermillimeter) - { - double value = (double) milliwattspermillimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromWattsPerCentimeter(double wattspercentimeter) - { - double value = (double) wattspercentimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromWattsPerFoot(double wattsperfoot) - { - double value = (double) wattsperfoot; - return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromWattsPerInch(double wattsperinch) - { - double value = (double) wattsperinch; - return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromWattsPerMeter(double wattspermeter) - { - double value = (double) wattspermeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LinearPowerDensity FromWattsPerMillimeter(double wattspermillimeter) - { - double value = (double) wattspermillimeter; - return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LinearPowerDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LinearPowerDensity From(double value, LinearPowerDensityUnit fromUnit) - { - return new LinearPowerDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LinearPowerDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LinearPowerDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LinearPowerDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out LinearPowerDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LinearPowerDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LinearPowerDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LinearPowerDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LinearPowerDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LinearPowerDensity objLinearPowerDensity)) throw new ArgumentException("Expected type LinearPowerDensity.", nameof(obj)); - - return CompareTo(objLinearPowerDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(LinearPowerDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is LinearPowerDensity objLinearPowerDensity)) - return false; - - return Equals(objLinearPowerDensity); - } - - public bool Equals(LinearPowerDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LinearPowerDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LinearPowerDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LinearPowerDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearPowerDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LinearPowerDensity to another LinearPowerDensity with the unit representation . - /// - /// A LinearPowerDensity with the specified unit. - public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LinearPowerDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LinearPowerDensityUnit.GigawattPerCentimeter: return (_value * 1e2) * 1e9d; - case LinearPowerDensityUnit.GigawattPerFoot: return (_value * 3.280839895) * 1e9d; - case LinearPowerDensityUnit.GigawattPerInch: return (_value * 39.37007874) * 1e9d; - case LinearPowerDensityUnit.GigawattPerMeter: return (_value) * 1e9d; - case LinearPowerDensityUnit.GigawattPerMillimeter: return (_value * 1e3) * 1e9d; - case LinearPowerDensityUnit.KilowattPerCentimeter: return (_value * 1e2) * 1e3d; - case LinearPowerDensityUnit.KilowattPerFoot: return (_value * 3.280839895) * 1e3d; - case LinearPowerDensityUnit.KilowattPerInch: return (_value * 39.37007874) * 1e3d; - case LinearPowerDensityUnit.KilowattPerMeter: return (_value) * 1e3d; - case LinearPowerDensityUnit.KilowattPerMillimeter: return (_value * 1e3) * 1e3d; - case LinearPowerDensityUnit.MegawattPerCentimeter: return (_value * 1e2) * 1e6d; - case LinearPowerDensityUnit.MegawattPerFoot: return (_value * 3.280839895) * 1e6d; - case LinearPowerDensityUnit.MegawattPerInch: return (_value * 39.37007874) * 1e6d; - case LinearPowerDensityUnit.MegawattPerMeter: return (_value) * 1e6d; - case LinearPowerDensityUnit.MegawattPerMillimeter: return (_value * 1e3) * 1e6d; - case LinearPowerDensityUnit.MilliwattPerCentimeter: return (_value * 1e2) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerFoot: return (_value * 3.280839895) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerInch: return (_value * 39.37007874) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMeter: return (_value) * 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMillimeter: return (_value * 1e3) * 1e-3d; - case LinearPowerDensityUnit.WattPerCentimeter: return _value * 1e2; - case LinearPowerDensityUnit.WattPerFoot: return _value * 3.280839895; - case LinearPowerDensityUnit.WattPerInch: return _value * 39.37007874; - case LinearPowerDensityUnit.WattPerMeter: return _value; - case LinearPowerDensityUnit.WattPerMillimeter: return _value * 1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LinearPowerDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LinearPowerDensityUnit.GigawattPerCentimeter: return (baseUnitValue / 1e2) / 1e9d; - case LinearPowerDensityUnit.GigawattPerFoot: return (baseUnitValue / 3.280839895) / 1e9d; - case LinearPowerDensityUnit.GigawattPerInch: return (baseUnitValue / 39.37007874) / 1e9d; - case LinearPowerDensityUnit.GigawattPerMeter: return (baseUnitValue) / 1e9d; - case LinearPowerDensityUnit.GigawattPerMillimeter: return (baseUnitValue / 1e3) / 1e9d; - case LinearPowerDensityUnit.KilowattPerCentimeter: return (baseUnitValue / 1e2) / 1e3d; - case LinearPowerDensityUnit.KilowattPerFoot: return (baseUnitValue / 3.280839895) / 1e3d; - case LinearPowerDensityUnit.KilowattPerInch: return (baseUnitValue / 39.37007874) / 1e3d; - case LinearPowerDensityUnit.KilowattPerMeter: return (baseUnitValue) / 1e3d; - case LinearPowerDensityUnit.KilowattPerMillimeter: return (baseUnitValue / 1e3) / 1e3d; - case LinearPowerDensityUnit.MegawattPerCentimeter: return (baseUnitValue / 1e2) / 1e6d; - case LinearPowerDensityUnit.MegawattPerFoot: return (baseUnitValue / 3.280839895) / 1e6d; - case LinearPowerDensityUnit.MegawattPerInch: return (baseUnitValue / 39.37007874) / 1e6d; - case LinearPowerDensityUnit.MegawattPerMeter: return (baseUnitValue) / 1e6d; - case LinearPowerDensityUnit.MegawattPerMillimeter: return (baseUnitValue / 1e3) / 1e6d; - case LinearPowerDensityUnit.MilliwattPerCentimeter: return (baseUnitValue / 1e2) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerFoot: return (baseUnitValue / 3.280839895) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerInch: return (baseUnitValue / 39.37007874) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMeter: return (baseUnitValue) / 1e-3d; - case LinearPowerDensityUnit.MilliwattPerMillimeter: return (baseUnitValue / 1e3) / 1e-3d; - case LinearPowerDensityUnit.WattPerCentimeter: return baseUnitValue / 1e2; - case LinearPowerDensityUnit.WattPerFoot: return baseUnitValue / 3.280839895; - case LinearPowerDensityUnit.WattPerInch: return baseUnitValue / 39.37007874; - case LinearPowerDensityUnit.WattPerMeter: return baseUnitValue; - case LinearPowerDensityUnit.WattPerMillimeter: return baseUnitValue / 1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Luminosity.g.cs deleted file mode 100644 index b72d6d2b1d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Luminosity.g.cs +++ /dev/null @@ -1,843 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object. - /// - /// - /// https://en.wikipedia.org/wiki/Luminosity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Luminosity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminosityUnit? _unit; - - static Luminosity() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = LuminosityUnit.Watt; - MaxValue = new Luminosity(double.MaxValue, BaseUnit); - MinValue = new Luminosity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Luminosity; - Units = Enum.GetValues(typeof(LuminosityUnit)).Cast().Except(new LuminosityUnit[]{ LuminosityUnit.Undefined }).ToArray(); - Zero = new Luminosity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Luminosity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Watt. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Luminosity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Luminosity(double value, LuminosityUnit unit) - { - if (unit == LuminosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Luminosity, which is Watt. All conversions go via this value. - /// - public static LuminosityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Luminosity - /// - public static Luminosity MaxValue { get; } - - /// - /// Represents the smallest possible value of Luminosity - /// - public static Luminosity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Luminosity quantity. - /// - public static LuminosityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Watt. - /// - public static Luminosity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Luminosity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Luminosity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Decawatts => As(LuminosityUnit.Decawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Deciwatts => As(LuminosityUnit.Deciwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Femtowatts => As(LuminosityUnit.Femtowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigawatts => As(LuminosityUnit.Gigawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilowatts => As(LuminosityUnit.Kilowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Megawatts => As(LuminosityUnit.Megawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Microwatts => As(LuminosityUnit.Microwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliwatts => As(LuminosityUnit.Milliwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanowatts => As(LuminosityUnit.Nanowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Petawatts => As(LuminosityUnit.Petawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Picowatts => As(LuminosityUnit.Picowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double SolarLuminosities => As(LuminosityUnit.SolarLuminosity); - - /// - /// Gets a value of this quantity converted into - /// - public double Terawatts => As(LuminosityUnit.Terawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Watts => As(LuminosityUnit.Watt); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LuminosityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LuminosityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromDecawatts(double decawatts) - { - double value = (double) decawatts; - return new Luminosity(value, LuminosityUnit.Decawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromDeciwatts(double deciwatts) - { - double value = (double) deciwatts; - return new Luminosity(value, LuminosityUnit.Deciwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromFemtowatts(double femtowatts) - { - double value = (double) femtowatts; - return new Luminosity(value, LuminosityUnit.Femtowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromGigawatts(double gigawatts) - { - double value = (double) gigawatts; - return new Luminosity(value, LuminosityUnit.Gigawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromKilowatts(double kilowatts) - { - double value = (double) kilowatts; - return new Luminosity(value, LuminosityUnit.Kilowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromMegawatts(double megawatts) - { - double value = (double) megawatts; - return new Luminosity(value, LuminosityUnit.Megawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromMicrowatts(double microwatts) - { - double value = (double) microwatts; - return new Luminosity(value, LuminosityUnit.Microwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromMilliwatts(double milliwatts) - { - double value = (double) milliwatts; - return new Luminosity(value, LuminosityUnit.Milliwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromNanowatts(double nanowatts) - { - double value = (double) nanowatts; - return new Luminosity(value, LuminosityUnit.Nanowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromPetawatts(double petawatts) - { - double value = (double) petawatts; - return new Luminosity(value, LuminosityUnit.Petawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromPicowatts(double picowatts) - { - double value = (double) picowatts; - return new Luminosity(value, LuminosityUnit.Picowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromSolarLuminosities(double solarluminosities) - { - double value = (double) solarluminosities; - return new Luminosity(value, LuminosityUnit.SolarLuminosity); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromTerawatts(double terawatts) - { - double value = (double) terawatts; - return new Luminosity(value, LuminosityUnit.Terawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Luminosity FromWatts(double watts) - { - double value = (double) watts; - return new Luminosity(value, LuminosityUnit.Watt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Luminosity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Luminosity From(double value, LuminosityUnit fromUnit) - { - return new Luminosity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Luminosity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Luminosity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Luminosity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Luminosity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminosityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LuminosityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LuminosityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LuminosityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Luminosity objLuminosity)) throw new ArgumentException("Expected type Luminosity.", nameof(obj)); - - return CompareTo(objLuminosity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Luminosity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Luminosity objLuminosity)) - return false; - - return Equals(objLuminosity); - } - - public bool Equals(Luminosity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Luminosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Luminosity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LuminosityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminosityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Luminosity to another Luminosity with the unit representation . - /// - /// A Luminosity with the specified unit. - public Luminosity ToUnit(LuminosityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Luminosity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LuminosityUnit.Decawatt: return (_value) * 1e1d; - case LuminosityUnit.Deciwatt: return (_value) * 1e-1d; - case LuminosityUnit.Femtowatt: return (_value) * 1e-15d; - case LuminosityUnit.Gigawatt: return (_value) * 1e9d; - case LuminosityUnit.Kilowatt: return (_value) * 1e3d; - case LuminosityUnit.Megawatt: return (_value) * 1e6d; - case LuminosityUnit.Microwatt: return (_value) * 1e-6d; - case LuminosityUnit.Milliwatt: return (_value) * 1e-3d; - case LuminosityUnit.Nanowatt: return (_value) * 1e-9d; - case LuminosityUnit.Petawatt: return (_value) * 1e15d; - case LuminosityUnit.Picowatt: return (_value) * 1e-12d; - case LuminosityUnit.SolarLuminosity: return _value * 3.846e26; - case LuminosityUnit.Terawatt: return (_value) * 1e12d; - case LuminosityUnit.Watt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminosityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminosityUnit.Decawatt: return (baseUnitValue) / 1e1d; - case LuminosityUnit.Deciwatt: return (baseUnitValue) / 1e-1d; - case LuminosityUnit.Femtowatt: return (baseUnitValue) / 1e-15d; - case LuminosityUnit.Gigawatt: return (baseUnitValue) / 1e9d; - case LuminosityUnit.Kilowatt: return (baseUnitValue) / 1e3d; - case LuminosityUnit.Megawatt: return (baseUnitValue) / 1e6d; - case LuminosityUnit.Microwatt: return (baseUnitValue) / 1e-6d; - case LuminosityUnit.Milliwatt: return (baseUnitValue) / 1e-3d; - case LuminosityUnit.Nanowatt: return (baseUnitValue) / 1e-9d; - case LuminosityUnit.Petawatt: return (baseUnitValue) / 1e15d; - case LuminosityUnit.Picowatt: return (baseUnitValue) / 1e-12d; - case LuminosityUnit.SolarLuminosity: return baseUnitValue / 3.846e26; - case LuminosityUnit.Terawatt: return (baseUnitValue) / 1e12d; - case LuminosityUnit.Watt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.g.cs deleted file mode 100644 index ff1866abb2..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousFlux.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. - /// - /// - /// https://en.wikipedia.org/wiki/Luminous_flux - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class LuminousFlux : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminousFluxUnit? _unit; - - static LuminousFlux() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - BaseUnit = LuminousFluxUnit.Lumen; - MaxValue = new LuminousFlux(double.MaxValue, BaseUnit); - MinValue = new LuminousFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.LuminousFlux; - Units = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); - Zero = new LuminousFlux(0, BaseUnit); - Info = new QuantityInfo(QuantityType.LuminousFlux, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Lumen. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public LuminousFlux() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private LuminousFlux(double value, LuminousFluxUnit unit) - { - if (unit == LuminousFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. - /// - public static LuminousFluxUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of LuminousFlux - /// - public static LuminousFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of LuminousFlux - /// - public static LuminousFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the LuminousFlux quantity. - /// - public static LuminousFluxUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. - /// - public static LuminousFlux Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => LuminousFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Lumens => As(LuminousFluxUnit.Lumen); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(LuminousFluxUnit.Lumen, new CultureInfo("en-US"), false, true, new string[]{"lm"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LuminousFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LuminousFlux FromLumens(double lumens) - { - double value = (double) lumens; - return new LuminousFlux(value, LuminousFluxUnit.Lumen); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LuminousFlux unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) - { - return new LuminousFlux((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LuminousFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LuminousFlux Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LuminousFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out LuminousFlux result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousFluxUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LuminousFluxUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LuminousFluxUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LuminousFlux objLuminousFlux)) throw new ArgumentException("Expected type LuminousFlux.", nameof(obj)); - - return CompareTo(objLuminousFlux); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(LuminousFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is LuminousFlux objLuminousFlux)) - return false; - - return Equals(objLuminousFlux); - } - - public bool Equals(LuminousFlux other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LuminousFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LuminousFluxUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousFluxUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LuminousFlux to another LuminousFlux with the unit representation . - /// - /// A LuminousFlux with the specified unit. - public LuminousFlux ToUnit(LuminousFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LuminousFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LuminousFluxUnit.Lumen: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminousFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminousFluxUnit.Lumen: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.g.cs deleted file mode 100644 index dec2aa0a17..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye. - /// - /// - /// https://en.wikipedia.org/wiki/Luminous_intensity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class LuminousIntensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly LuminousIntensityUnit? _unit; - - static LuminousIntensity() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - BaseUnit = LuminousIntensityUnit.Candela; - MaxValue = new LuminousIntensity(double.MaxValue, BaseUnit); - MinValue = new LuminousIntensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.LuminousIntensity; - Units = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); - Zero = new LuminousIntensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.LuminousIntensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Candela. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public LuminousIntensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private LuminousIntensity(double value, LuminousIntensityUnit unit) - { - if (unit == LuminousIntensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. - /// - public static LuminousIntensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of LuminousIntensity - /// - public static LuminousIntensity MaxValue { get; } - - /// - /// Represents the smallest possible value of LuminousIntensity - /// - public static LuminousIntensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the LuminousIntensity quantity. - /// - public static LuminousIntensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Candela. - /// - public static LuminousIntensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => LuminousIntensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Candela => As(LuminousIntensityUnit.Candela); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(LuminousIntensityUnit.Candela, new CultureInfo("en-US"), false, true, new string[]{"cd"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(LuminousIntensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static LuminousIntensity FromCandela(double candela) - { - double value = (double) candela; - return new LuminousIntensity(value, LuminousIntensityUnit.Candela); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// LuminousIntensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static LuminousIntensity From(double value, LuminousIntensityUnit fromUnit) - { - return new LuminousIntensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static LuminousIntensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LuminousIntensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out LuminousIntensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out LuminousIntensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static LuminousIntensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LuminousIntensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LuminousIntensity objLuminousIntensity)) throw new ArgumentException("Expected type LuminousIntensity.", nameof(obj)); - - return CompareTo(objLuminousIntensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(LuminousIntensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is LuminousIntensity objLuminousIntensity)) - return false; - - return Equals(objLuminousIntensity); - } - - public bool Equals(LuminousIntensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another LuminousIntensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(LuminousIntensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousIntensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((LuminousIntensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousIntensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation . - /// - /// A LuminousIntensity with the specified unit. - public LuminousIntensity ToUnit(LuminousIntensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new LuminousIntensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case LuminousIntensityUnit.Candela: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(LuminousIntensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case LuminousIntensityUnit.Candela: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.g.cs deleted file mode 100644 index 7a73a4f1f0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticField.g.cs +++ /dev/null @@ -1,691 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles. - /// - /// - /// https://en.wikipedia.org/wiki/Magnetic_field - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MagneticField : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagneticFieldUnit? _unit; - - static MagneticField() - { - BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); - BaseUnit = MagneticFieldUnit.Tesla; - MaxValue = new MagneticField(double.MaxValue, BaseUnit); - MinValue = new MagneticField(double.MinValue, BaseUnit); - QuantityType = QuantityType.MagneticField; - Units = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); - Zero = new MagneticField(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MagneticField, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Tesla. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MagneticField() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MagneticField(double value, MagneticFieldUnit unit) - { - if (unit == MagneticFieldUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MagneticField, which is Tesla. All conversions go via this value. - /// - public static MagneticFieldUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MagneticField - /// - public static MagneticField MaxValue { get; } - - /// - /// Represents the smallest possible value of MagneticField - /// - public static MagneticField MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MagneticField quantity. - /// - public static MagneticFieldUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. - /// - public static MagneticField Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MagneticField.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MagneticField.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Gausses => As(MagneticFieldUnit.Gauss); - - /// - /// Gets a value of this quantity converted into - /// - public double Microteslas => As(MagneticFieldUnit.Microtesla); - - /// - /// Gets a value of this quantity converted into - /// - public double Milligausses => As(MagneticFieldUnit.Milligauss); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliteslas => As(MagneticFieldUnit.Millitesla); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); - - /// - /// Gets a value of this quantity converted into - /// - public double Teslas => As(MagneticFieldUnit.Tesla); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MagneticFieldUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromGausses(double gausses) - { - double value = (double) gausses; - return new MagneticField(value, MagneticFieldUnit.Gauss); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromMicroteslas(double microteslas) - { - double value = (double) microteslas; - return new MagneticField(value, MagneticFieldUnit.Microtesla); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromMilligausses(double milligausses) - { - double value = (double) milligausses; - return new MagneticField(value, MagneticFieldUnit.Milligauss); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromMilliteslas(double milliteslas) - { - double value = (double) milliteslas; - return new MagneticField(value, MagneticFieldUnit.Millitesla); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromNanoteslas(double nanoteslas) - { - double value = (double) nanoteslas; - return new MagneticField(value, MagneticFieldUnit.Nanotesla); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticField FromTeslas(double teslas) - { - double value = (double) teslas; - return new MagneticField(value, MagneticFieldUnit.Tesla); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MagneticField unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MagneticField From(double value, MagneticFieldUnit fromUnit) - { - return new MagneticField((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MagneticField Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MagneticField Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MagneticField result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MagneticField result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFieldUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MagneticFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MagneticFieldUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MagneticFieldUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MagneticField objMagneticField)) throw new ArgumentException("Expected type MagneticField.", nameof(obj)); - - return CompareTo(objMagneticField); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MagneticField other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MagneticField objMagneticField)) - return false; - - return Equals(objMagneticField); - } - - public bool Equals(MagneticField other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MagneticField within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MagneticField other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticField. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MagneticFieldUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFieldUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MagneticField to another MagneticField with the unit representation . - /// - /// A MagneticField with the specified unit. - public MagneticField ToUnit(MagneticFieldUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MagneticField(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MagneticFieldUnit.Gauss: return _value / 1e4; - case MagneticFieldUnit.Microtesla: return (_value) * 1e-6d; - case MagneticFieldUnit.Milligauss: return (_value / 1e4) * 1e-3d; - case MagneticFieldUnit.Millitesla: return (_value) * 1e-3d; - case MagneticFieldUnit.Nanotesla: return (_value) * 1e-9d; - case MagneticFieldUnit.Tesla: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagneticFieldUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagneticFieldUnit.Gauss: return baseUnitValue * 1e4; - case MagneticFieldUnit.Microtesla: return (baseUnitValue) / 1e-6d; - case MagneticFieldUnit.Milligauss: return (baseUnitValue * 1e4) / 1e-3d; - case MagneticFieldUnit.Millitesla: return (baseUnitValue) / 1e-3d; - case MagneticFieldUnit.Nanotesla: return (baseUnitValue) / 1e-9d; - case MagneticFieldUnit.Tesla: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.g.cs deleted file mode 100644 index 863834d7e5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MagneticFlux.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface. - /// - /// - /// https://en.wikipedia.org/wiki/Magnetic_flux - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MagneticFlux : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagneticFluxUnit? _unit; - - static MagneticFlux() - { - BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); - BaseUnit = MagneticFluxUnit.Weber; - MaxValue = new MagneticFlux(double.MaxValue, BaseUnit); - MinValue = new MagneticFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.MagneticFlux; - Units = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); - Zero = new MagneticFlux(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MagneticFlux, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Weber. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MagneticFlux() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MagneticFlux(double value, MagneticFluxUnit unit) - { - if (unit == MagneticFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. - /// - public static MagneticFluxUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MagneticFlux - /// - public static MagneticFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of MagneticFlux - /// - public static MagneticFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MagneticFlux quantity. - /// - public static MagneticFluxUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Weber. - /// - public static MagneticFlux Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MagneticFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Webers => As(MagneticFluxUnit.Weber); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFluxUnit.Weber, new CultureInfo("en-US"), false, true, new string[]{"Wb"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MagneticFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MagneticFlux FromWebers(double webers) - { - double value = (double) webers; - return new MagneticFlux(value, MagneticFluxUnit.Weber); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MagneticFlux unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) - { - return new MagneticFlux((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MagneticFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MagneticFlux Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MagneticFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MagneticFlux result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagneticFluxUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MagneticFluxUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MagneticFluxUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MagneticFlux objMagneticFlux)) throw new ArgumentException("Expected type MagneticFlux.", nameof(obj)); - - return CompareTo(objMagneticFlux); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MagneticFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MagneticFlux objMagneticFlux)) - return false; - - return Equals(objMagneticFlux); - } - - public bool Equals(MagneticFlux other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MagneticFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MagneticFluxUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFluxUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MagneticFlux to another MagneticFlux with the unit representation . - /// - /// A MagneticFlux with the specified unit. - public MagneticFlux ToUnit(MagneticFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MagneticFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MagneticFluxUnit.Weber: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagneticFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagneticFluxUnit.Weber: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.g.cs deleted file mode 100644 index f8bdd62dab..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Magnetization.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material. - /// - /// - /// https://en.wikipedia.org/wiki/Magnetization - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Magnetization : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MagnetizationUnit? _unit; - - static Magnetization() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); - BaseUnit = MagnetizationUnit.AmperePerMeter; - MaxValue = new Magnetization(double.MaxValue, BaseUnit); - MinValue = new Magnetization(double.MinValue, BaseUnit); - QuantityType = QuantityType.Magnetization; - Units = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); - Zero = new Magnetization(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Magnetization, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit AmperePerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Magnetization() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Magnetization(double value, MagnetizationUnit unit) - { - if (unit == MagnetizationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. - /// - public static MagnetizationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Magnetization - /// - public static Magnetization MaxValue { get; } - - /// - /// Represents the smallest possible value of Magnetization - /// - public static Magnetization MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Magnetization quantity. - /// - public static MagnetizationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. - /// - public static Magnetization Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Magnetization.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Magnetization.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(MagnetizationUnit.AmperePerMeter, new CultureInfo("en-US"), false, true, new string[]{"A/m"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MagnetizationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Magnetization FromAmperesPerMeter(double amperespermeter) - { - double value = (double) amperespermeter; - return new Magnetization(value, MagnetizationUnit.AmperePerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Magnetization unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Magnetization From(double value, MagnetizationUnit fromUnit) - { - return new Magnetization((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Magnetization Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Magnetization Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Magnetization result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Magnetization result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MagnetizationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MagnetizationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MagnetizationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MagnetizationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Magnetization objMagnetization)) throw new ArgumentException("Expected type Magnetization.", nameof(obj)); - - return CompareTo(objMagnetization); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Magnetization other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Magnetization objMagnetization)) - return false; - - return Equals(objMagnetization); - } - - public bool Equals(Magnetization other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Magnetization within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Magnetization other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Magnetization. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MagnetizationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagnetizationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Magnetization to another Magnetization with the unit representation . - /// - /// A Magnetization with the specified unit. - public Magnetization ToUnit(MagnetizationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Magnetization(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MagnetizationUnit.AmperePerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MagnetizationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MagnetizationUnit.AmperePerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.g.cs deleted file mode 100644 index 2551e71207..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Mass.g.cs +++ /dev/null @@ -1,1084 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Mass : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassUnit? _unit; - - static Mass() - { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); - BaseUnit = MassUnit.Kilogram; - MaxValue = new Mass(double.MaxValue, BaseUnit); - MinValue = new Mass(double.MinValue, BaseUnit); - QuantityType = QuantityType.Mass; - Units = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); - Zero = new Mass(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Mass, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Kilogram. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Mass() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Mass(double value, MassUnit unit) - { - if (unit == MassUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Mass, which is Kilogram. All conversions go via this value. - /// - public static MassUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Mass - /// - public static Mass MaxValue { get; } - - /// - /// Represents the smallest possible value of Mass - /// - public static Mass MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Mass quantity. - /// - public static MassUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. - /// - public static Mass Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Mass.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Mass.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Centigrams => As(MassUnit.Centigram); - - /// - /// Gets a value of this quantity converted into - /// - public double Decagrams => As(MassUnit.Decagram); - - /// - /// Gets a value of this quantity converted into - /// - public double Decigrams => As(MassUnit.Decigram); - - /// - /// Gets a value of this quantity converted into - /// - public double EarthMasses => As(MassUnit.EarthMass); - - /// - /// Gets a value of this quantity converted into - /// - public double Grains => As(MassUnit.Grain); - - /// - /// Gets a value of this quantity converted into - /// - public double Grams => As(MassUnit.Gram); - - /// - /// Gets a value of this quantity converted into - /// - public double Hectograms => As(MassUnit.Hectogram); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilograms => As(MassUnit.Kilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilopounds => As(MassUnit.Kilopound); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilotonnes => As(MassUnit.Kilotonne); - - /// - /// Gets a value of this quantity converted into - /// - public double LongHundredweight => As(MassUnit.LongHundredweight); - - /// - /// Gets a value of this quantity converted into - /// - public double LongTons => As(MassUnit.LongTon); - - /// - /// Gets a value of this quantity converted into - /// - public double Megapounds => As(MassUnit.Megapound); - - /// - /// Gets a value of this quantity converted into - /// - public double Megatonnes => As(MassUnit.Megatonne); - - /// - /// Gets a value of this quantity converted into - /// - public double Micrograms => As(MassUnit.Microgram); - - /// - /// Gets a value of this quantity converted into - /// - public double Milligrams => As(MassUnit.Milligram); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanograms => As(MassUnit.Nanogram); - - /// - /// Gets a value of this quantity converted into - /// - public double Ounces => As(MassUnit.Ounce); - - /// - /// Gets a value of this quantity converted into - /// - public double Pounds => As(MassUnit.Pound); - - /// - /// Gets a value of this quantity converted into - /// - public double ShortHundredweight => As(MassUnit.ShortHundredweight); - - /// - /// Gets a value of this quantity converted into - /// - public double ShortTons => As(MassUnit.ShortTon); - - /// - /// Gets a value of this quantity converted into - /// - public double Slugs => As(MassUnit.Slug); - - /// - /// Gets a value of this quantity converted into - /// - public double SolarMasses => As(MassUnit.SolarMass); - - /// - /// Gets a value of this quantity converted into - /// - public double Stone => As(MassUnit.Stone); - - /// - /// Gets a value of this quantity converted into - /// - public double Tonnes => As(MassUnit.Tonne); - - #endregion - - #region Static Methods - - 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[]{"吨"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MassUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MassUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromCentigrams(double centigrams) - { - double value = (double) centigrams; - return new Mass(value, MassUnit.Centigram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromDecagrams(double decagrams) - { - double value = (double) decagrams; - return new Mass(value, MassUnit.Decagram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromDecigrams(double decigrams) - { - double value = (double) decigrams; - return new Mass(value, MassUnit.Decigram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromEarthMasses(double earthmasses) - { - double value = (double) earthmasses; - return new Mass(value, MassUnit.EarthMass); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromGrains(double grains) - { - double value = (double) grains; - return new Mass(value, MassUnit.Grain); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromGrams(double grams) - { - double value = (double) grams; - return new Mass(value, MassUnit.Gram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromHectograms(double hectograms) - { - double value = (double) hectograms; - return new Mass(value, MassUnit.Hectogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilograms(double kilograms) - { - double value = (double) kilograms; - return new Mass(value, MassUnit.Kilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilopounds(double kilopounds) - { - double value = (double) kilopounds; - return new Mass(value, MassUnit.Kilopound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromKilotonnes(double kilotonnes) - { - double value = (double) kilotonnes; - return new Mass(value, MassUnit.Kilotonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromLongHundredweight(double longhundredweight) - { - double value = (double) longhundredweight; - return new Mass(value, MassUnit.LongHundredweight); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromLongTons(double longtons) - { - double value = (double) longtons; - return new Mass(value, MassUnit.LongTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMegapounds(double megapounds) - { - double value = (double) megapounds; - return new Mass(value, MassUnit.Megapound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMegatonnes(double megatonnes) - { - double value = (double) megatonnes; - return new Mass(value, MassUnit.Megatonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMicrograms(double micrograms) - { - double value = (double) micrograms; - return new Mass(value, MassUnit.Microgram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromMilligrams(double milligrams) - { - double value = (double) milligrams; - return new Mass(value, MassUnit.Milligram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromNanograms(double nanograms) - { - double value = (double) nanograms; - return new Mass(value, MassUnit.Nanogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromOunces(double ounces) - { - double value = (double) ounces; - return new Mass(value, MassUnit.Ounce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromPounds(double pounds) - { - double value = (double) pounds; - return new Mass(value, MassUnit.Pound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromShortHundredweight(double shorthundredweight) - { - double value = (double) shorthundredweight; - return new Mass(value, MassUnit.ShortHundredweight); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromShortTons(double shorttons) - { - double value = (double) shorttons; - return new Mass(value, MassUnit.ShortTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromSlugs(double slugs) - { - double value = (double) slugs; - return new Mass(value, MassUnit.Slug); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromSolarMasses(double solarmasses) - { - double value = (double) solarmasses; - return new Mass(value, MassUnit.SolarMass); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromStone(double stone) - { - double value = (double) stone; - return new Mass(value, MassUnit.Stone); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Mass FromTonnes(double tonnes) - { - double value = (double) tonnes; - return new Mass(value, MassUnit.Tonne); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Mass unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Mass From(double value, MassUnit fromUnit) - { - return new Mass((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Mass Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Mass Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Mass result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Mass result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MassUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MassUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Mass objMass)) throw new ArgumentException("Expected type Mass.", nameof(obj)); - - return CompareTo(objMass); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Mass other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Mass objMass)) - return false; - - return Equals(objMass); - } - - public bool Equals(Mass other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Mass within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Mass. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MassUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Mass to another Mass with the unit representation . - /// - /// A Mass with the specified unit. - public Mass ToUnit(MassUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Mass(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassUnit.Centigram: return (_value / 1e3) * 1e-2d; - case MassUnit.Decagram: return (_value / 1e3) * 1e1d; - case MassUnit.Decigram: return (_value / 1e3) * 1e-1d; - case MassUnit.EarthMass: return _value * 5.9722E+24; - case MassUnit.Grain: return _value / 15432.358352941431; - case MassUnit.Gram: return _value / 1e3; - case MassUnit.Hectogram: return (_value / 1e3) * 1e2d; - case MassUnit.Kilogram: return (_value / 1e3) * 1e3d; - case MassUnit.Kilopound: return (_value * 0.45359237) * 1e3d; - case MassUnit.Kilotonne: return (_value * 1e3) * 1e3d; - case MassUnit.LongHundredweight: return _value / 0.01968413055222121; - case MassUnit.LongTon: return _value * 1.0160469088e3; - case MassUnit.Megapound: return (_value * 0.45359237) * 1e6d; - case MassUnit.Megatonne: return (_value * 1e3) * 1e6d; - case MassUnit.Microgram: return (_value / 1e3) * 1e-6d; - case MassUnit.Milligram: return (_value / 1e3) * 1e-3d; - case MassUnit.Nanogram: return (_value / 1e3) * 1e-9d; - case MassUnit.Ounce: return _value / 35.2739619; - case MassUnit.Pound: return _value * 0.45359237; - case MassUnit.ShortHundredweight: return _value / 0.022046226218487758; - case MassUnit.ShortTon: return _value * 9.0718474e2; - case MassUnit.Slug: return _value / 6.852176556196105e-2; - case MassUnit.SolarMass: return _value * 1.98947e30; - case MassUnit.Stone: return _value / 0.1574731728702698; - case MassUnit.Tonne: return _value * 1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassUnit.Centigram: return (baseUnitValue * 1e3) / 1e-2d; - case MassUnit.Decagram: return (baseUnitValue * 1e3) / 1e1d; - case MassUnit.Decigram: return (baseUnitValue * 1e3) / 1e-1d; - case MassUnit.EarthMass: return baseUnitValue / 5.9722E+24; - case MassUnit.Grain: return baseUnitValue * 15432.358352941431; - case MassUnit.Gram: return baseUnitValue * 1e3; - case MassUnit.Hectogram: return (baseUnitValue * 1e3) / 1e2d; - case MassUnit.Kilogram: return (baseUnitValue * 1e3) / 1e3d; - case MassUnit.Kilopound: return (baseUnitValue / 0.45359237) / 1e3d; - case MassUnit.Kilotonne: return (baseUnitValue / 1e3) / 1e3d; - case MassUnit.LongHundredweight: return baseUnitValue * 0.01968413055222121; - case MassUnit.LongTon: return baseUnitValue / 1.0160469088e3; - case MassUnit.Megapound: return (baseUnitValue / 0.45359237) / 1e6d; - case MassUnit.Megatonne: return (baseUnitValue / 1e3) / 1e6d; - case MassUnit.Microgram: return (baseUnitValue * 1e3) / 1e-6d; - case MassUnit.Milligram: return (baseUnitValue * 1e3) / 1e-3d; - case MassUnit.Nanogram: return (baseUnitValue * 1e3) / 1e-9d; - case MassUnit.Ounce: return baseUnitValue * 35.2739619; - case MassUnit.Pound: return baseUnitValue / 0.45359237; - case MassUnit.ShortHundredweight: return baseUnitValue * 0.022046226218487758; - case MassUnit.ShortTon: return baseUnitValue / 9.0718474e2; - case MassUnit.Slug: return baseUnitValue * 6.852176556196105e-2; - case MassUnit.SolarMass: return baseUnitValue / 1.98947e30; - case MassUnit.Stone: return baseUnitValue * 0.1574731728702698; - case MassUnit.Tonne: return baseUnitValue / 1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassConcentration.g.cs deleted file mode 100644 index 2badfefbd7..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassConcentration.g.cs +++ /dev/null @@ -1,1512 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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 - /// - /// - /// https://en.wikipedia.org/wiki/Mass_concentration_(chemistry) - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassConcentration : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassConcentrationUnit? _unit; - - static MassConcentration() - { - BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); - BaseUnit = MassConcentrationUnit.KilogramPerCubicMeter; - MaxValue = new MassConcentration(double.MaxValue, BaseUnit); - MinValue = new MassConcentration(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassConcentration; - Units = Enum.GetValues(typeof(MassConcentrationUnit)).Cast().Except(new MassConcentrationUnit[]{ MassConcentrationUnit.Undefined }).ToArray(); - Zero = new MassConcentration(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MassConcentration, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerCubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MassConcentration() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MassConcentration(double value, MassConcentrationUnit unit) - { - if (unit == MassConcentrationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MassConcentration, which is KilogramPerCubicMeter. All conversions go via this value. - /// - public static MassConcentrationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MassConcentration - /// - public static MassConcentration MaxValue { get; } - - /// - /// Represents the smallest possible value of MassConcentration - /// - public static MassConcentration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MassConcentration quantity. - /// - public static MassConcentrationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. - /// - public static MassConcentration Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MassConcentration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassConcentration.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerDeciliter => As(MassConcentrationUnit.CentigramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerLiter => As(MassConcentrationUnit.CentigramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerMicroliter => As(MassConcentrationUnit.CentigramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerMilliliter => As(MassConcentrationUnit.CentigramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerDeciliter => As(MassConcentrationUnit.DecigramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerLiter => As(MassConcentrationUnit.DecigramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerMicroliter => As(MassConcentrationUnit.DecigramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerMilliliter => As(MassConcentrationUnit.DecigramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicCentimeter => As(MassConcentrationUnit.GramPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicMeter => As(MassConcentrationUnit.GramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerCubicMillimeter => As(MassConcentrationUnit.GramPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerDeciliter => As(MassConcentrationUnit.GramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerLiter => As(MassConcentrationUnit.GramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerMicroliter => As(MassConcentrationUnit.GramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerMilliliter => As(MassConcentrationUnit.GramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCubicCentimeter => As(MassConcentrationUnit.KilogramPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCubicMeter => As(MassConcentrationUnit.KilogramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerCubicMillimeter => As(MassConcentrationUnit.KilogramPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerLiter => As(MassConcentrationUnit.KilogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsPerCubicFoot => As(MassConcentrationUnit.KilopoundPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsPerCubicInch => As(MassConcentrationUnit.KilopoundPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerCubicMeter => As(MassConcentrationUnit.MicrogramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerDeciliter => As(MassConcentrationUnit.MicrogramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerLiter => As(MassConcentrationUnit.MicrogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerMicroliter => As(MassConcentrationUnit.MicrogramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerMilliliter => As(MassConcentrationUnit.MicrogramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerCubicMeter => As(MassConcentrationUnit.MilligramPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerDeciliter => As(MassConcentrationUnit.MilligramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerLiter => As(MassConcentrationUnit.MilligramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerMicroliter => As(MassConcentrationUnit.MilligramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerMilliliter => As(MassConcentrationUnit.MilligramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerDeciliter => As(MassConcentrationUnit.NanogramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerLiter => As(MassConcentrationUnit.NanogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerMicroliter => As(MassConcentrationUnit.NanogramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerMilliliter => As(MassConcentrationUnit.NanogramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double OuncesPerImperialGallon => As(MassConcentrationUnit.OuncePerImperialGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double OuncesPerUSGallon => As(MassConcentrationUnit.OuncePerUSGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerDeciliter => As(MassConcentrationUnit.PicogramPerDeciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerLiter => As(MassConcentrationUnit.PicogramPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerMicroliter => As(MassConcentrationUnit.PicogramPerMicroliter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicogramsPerMilliliter => As(MassConcentrationUnit.PicogramPerMilliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicFoot => As(MassConcentrationUnit.PoundPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerCubicInch => As(MassConcentrationUnit.PoundPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerImperialGallon => As(MassConcentrationUnit.PoundPerImperialGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerUSGallon => As(MassConcentrationUnit.PoundPerUSGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugsPerCubicFoot => As(MassConcentrationUnit.SlugPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicCentimeter => As(MassConcentrationUnit.TonnePerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicMeter => As(MassConcentrationUnit.TonnePerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerCubicMillimeter => As(MassConcentrationUnit.TonnePerCubicMillimeter); - - #endregion - - #region Static Methods - - 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³"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MassConcentrationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MassConcentrationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromCentigramsPerDeciliter(double centigramsperdeciliter) - { - double value = (double) centigramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.CentigramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromCentigramsPerLiter(double centigramsperliter) - { - double value = (double) centigramsperliter; - return new MassConcentration(value, MassConcentrationUnit.CentigramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromCentigramsPerMicroliter(double centigramspermicroliter) - { - double value = (double) centigramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.CentigramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromCentigramsPerMilliliter(double centigramspermilliliter) - { - double value = (double) centigramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.CentigramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromDecigramsPerDeciliter(double decigramsperdeciliter) - { - double value = (double) decigramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.DecigramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromDecigramsPerLiter(double decigramsperliter) - { - double value = (double) decigramsperliter; - return new MassConcentration(value, MassConcentrationUnit.DecigramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromDecigramsPerMicroliter(double decigramspermicroliter) - { - double value = (double) decigramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.DecigramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromDecigramsPerMilliliter(double decigramspermilliliter) - { - double value = (double) decigramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.DecigramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerCubicCentimeter(double gramspercubiccentimeter) - { - double value = (double) gramspercubiccentimeter; - return new MassConcentration(value, MassConcentrationUnit.GramPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerCubicMeter(double gramspercubicmeter) - { - double value = (double) gramspercubicmeter; - return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerCubicMillimeter(double gramspercubicmillimeter) - { - double value = (double) gramspercubicmillimeter; - return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerDeciliter(double gramsperdeciliter) - { - double value = (double) gramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.GramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerLiter(double gramsperliter) - { - double value = (double) gramsperliter; - return new MassConcentration(value, MassConcentrationUnit.GramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerMicroliter(double gramspermicroliter) - { - double value = (double) gramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.GramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromGramsPerMilliliter(double gramspermilliliter) - { - double value = (double) gramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.GramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) - { - double value = (double) kilogramspercubiccentimeter; - return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromKilogramsPerCubicMeter(double kilogramspercubicmeter) - { - double value = (double) kilogramspercubicmeter; - return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) - { - double value = (double) kilogramspercubicmillimeter; - return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromKilogramsPerLiter(double kilogramsperliter) - { - double value = (double) kilogramsperliter; - return new MassConcentration(value, MassConcentrationUnit.KilogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) - { - double value = (double) kilopoundspercubicfoot; - return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromKilopoundsPerCubicInch(double kilopoundspercubicinch) - { - double value = (double) kilopoundspercubicinch; - return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMicrogramsPerCubicMeter(double microgramspercubicmeter) - { - double value = (double) microgramspercubicmeter; - return new MassConcentration(value, MassConcentrationUnit.MicrogramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMicrogramsPerDeciliter(double microgramsperdeciliter) - { - double value = (double) microgramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.MicrogramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMicrogramsPerLiter(double microgramsperliter) - { - double value = (double) microgramsperliter; - return new MassConcentration(value, MassConcentrationUnit.MicrogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMicrogramsPerMicroliter(double microgramspermicroliter) - { - double value = (double) microgramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMicrogramsPerMilliliter(double microgramspermilliliter) - { - double value = (double) microgramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMilligramsPerCubicMeter(double milligramspercubicmeter) - { - double value = (double) milligramspercubicmeter; - return new MassConcentration(value, MassConcentrationUnit.MilligramPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMilligramsPerDeciliter(double milligramsperdeciliter) - { - double value = (double) milligramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.MilligramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMilligramsPerLiter(double milligramsperliter) - { - double value = (double) milligramsperliter; - return new MassConcentration(value, MassConcentrationUnit.MilligramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMilligramsPerMicroliter(double milligramspermicroliter) - { - double value = (double) milligramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.MilligramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromMilligramsPerMilliliter(double milligramspermilliliter) - { - double value = (double) milligramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.MilligramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromNanogramsPerDeciliter(double nanogramsperdeciliter) - { - double value = (double) nanogramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.NanogramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromNanogramsPerLiter(double nanogramsperliter) - { - double value = (double) nanogramsperliter; - return new MassConcentration(value, MassConcentrationUnit.NanogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromNanogramsPerMicroliter(double nanogramspermicroliter) - { - double value = (double) nanogramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.NanogramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromNanogramsPerMilliliter(double nanogramspermilliliter) - { - double value = (double) nanogramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.NanogramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromOuncesPerImperialGallon(double ouncesperimperialgallon) - { - double value = (double) ouncesperimperialgallon; - return new MassConcentration(value, MassConcentrationUnit.OuncePerImperialGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromOuncesPerUSGallon(double ouncesperusgallon) - { - double value = (double) ouncesperusgallon; - return new MassConcentration(value, MassConcentrationUnit.OuncePerUSGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPicogramsPerDeciliter(double picogramsperdeciliter) - { - double value = (double) picogramsperdeciliter; - return new MassConcentration(value, MassConcentrationUnit.PicogramPerDeciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPicogramsPerLiter(double picogramsperliter) - { - double value = (double) picogramsperliter; - return new MassConcentration(value, MassConcentrationUnit.PicogramPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPicogramsPerMicroliter(double picogramspermicroliter) - { - double value = (double) picogramspermicroliter; - return new MassConcentration(value, MassConcentrationUnit.PicogramPerMicroliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPicogramsPerMilliliter(double picogramspermilliliter) - { - double value = (double) picogramspermilliliter; - return new MassConcentration(value, MassConcentrationUnit.PicogramPerMilliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPoundsPerCubicFoot(double poundspercubicfoot) - { - double value = (double) poundspercubicfoot; - return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPoundsPerCubicInch(double poundspercubicinch) - { - double value = (double) poundspercubicinch; - return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPoundsPerImperialGallon(double poundsperimperialgallon) - { - double value = (double) poundsperimperialgallon; - return new MassConcentration(value, MassConcentrationUnit.PoundPerImperialGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromPoundsPerUSGallon(double poundsperusgallon) - { - double value = (double) poundsperusgallon; - return new MassConcentration(value, MassConcentrationUnit.PoundPerUSGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromSlugsPerCubicFoot(double slugspercubicfoot) - { - double value = (double) slugspercubicfoot; - return new MassConcentration(value, MassConcentrationUnit.SlugPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) - { - double value = (double) tonnespercubiccentimeter; - return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromTonnesPerCubicMeter(double tonnespercubicmeter) - { - double value = (double) tonnespercubicmeter; - return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassConcentration FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) - { - double value = (double) tonnespercubicmillimeter; - return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassConcentration unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassConcentration From(double value, MassConcentrationUnit fromUnit) - { - return new MassConcentration((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassConcentration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassConcentration Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassConcentration result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MassConcentration result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassConcentrationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassConcentrationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MassConcentrationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MassConcentrationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassConcentration objMassConcentration)) throw new ArgumentException("Expected type MassConcentration.", nameof(obj)); - - return CompareTo(objMassConcentration); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MassConcentration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassConcentration objMassConcentration)) - return false; - - return Equals(objMassConcentration); - } - - public bool Equals(MassConcentration other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassConcentration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassConcentration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MassConcentrationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassConcentrationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassConcentration to another MassConcentration with the unit representation . - /// - /// A MassConcentration with the specified unit. - public MassConcentration ToUnit(MassConcentrationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassConcentration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassConcentrationUnit.CentigramPerDeciliter: return (_value / 1e-1) * 1e-2d; - case MassConcentrationUnit.CentigramPerLiter: return (_value) * 1e-2d; - case MassConcentrationUnit.CentigramPerMicroliter: return (_value / 1e-6) * 1e-2d; - case MassConcentrationUnit.CentigramPerMilliliter: return (_value / 1e-3) * 1e-2d; - case MassConcentrationUnit.DecigramPerDeciliter: return (_value / 1e-1) * 1e-1d; - case MassConcentrationUnit.DecigramPerLiter: return (_value) * 1e-1d; - case MassConcentrationUnit.DecigramPerMicroliter: return (_value / 1e-6) * 1e-1d; - case MassConcentrationUnit.DecigramPerMilliliter: return (_value / 1e-3) * 1e-1d; - case MassConcentrationUnit.GramPerCubicCentimeter: return _value / 1e-3; - case MassConcentrationUnit.GramPerCubicMeter: return _value / 1e3; - case MassConcentrationUnit.GramPerCubicMillimeter: return _value / 1e-6; - case MassConcentrationUnit.GramPerDeciliter: return _value / 1e-1; - case MassConcentrationUnit.GramPerLiter: return _value; - case MassConcentrationUnit.GramPerMicroliter: return _value / 1e-6; - case MassConcentrationUnit.GramPerMilliliter: return _value / 1e-3; - case MassConcentrationUnit.KilogramPerCubicCentimeter: return (_value / 1e-3) * 1e3d; - case MassConcentrationUnit.KilogramPerCubicMeter: return (_value / 1e3) * 1e3d; - case MassConcentrationUnit.KilogramPerCubicMillimeter: return (_value / 1e-6) * 1e3d; - case MassConcentrationUnit.KilogramPerLiter: return (_value) * 1e3d; - case MassConcentrationUnit.KilopoundPerCubicFoot: return (_value / 0.062427961) * 1e3d; - case MassConcentrationUnit.KilopoundPerCubicInch: return (_value / 3.6127298147753e-5) * 1e3d; - case MassConcentrationUnit.MicrogramPerCubicMeter: return (_value / 1e3) * 1e-6d; - case MassConcentrationUnit.MicrogramPerDeciliter: return (_value / 1e-1) * 1e-6d; - case MassConcentrationUnit.MicrogramPerLiter: return (_value) * 1e-6d; - case MassConcentrationUnit.MicrogramPerMicroliter: return (_value / 1e-6) * 1e-6d; - case MassConcentrationUnit.MicrogramPerMilliliter: return (_value / 1e-3) * 1e-6d; - case MassConcentrationUnit.MilligramPerCubicMeter: return (_value / 1e3) * 1e-3d; - case MassConcentrationUnit.MilligramPerDeciliter: return (_value / 1e-1) * 1e-3d; - case MassConcentrationUnit.MilligramPerLiter: return (_value) * 1e-3d; - case MassConcentrationUnit.MilligramPerMicroliter: return (_value / 1e-6) * 1e-3d; - case MassConcentrationUnit.MilligramPerMilliliter: return (_value / 1e-3) * 1e-3d; - case MassConcentrationUnit.NanogramPerDeciliter: return (_value / 1e-1) * 1e-9d; - case MassConcentrationUnit.NanogramPerLiter: return (_value) * 1e-9d; - case MassConcentrationUnit.NanogramPerMicroliter: return (_value / 1e-6) * 1e-9d; - case MassConcentrationUnit.NanogramPerMilliliter: return (_value / 1e-3) * 1e-9d; - case MassConcentrationUnit.OuncePerImperialGallon: return _value / 0.1603586720609; - case MassConcentrationUnit.OuncePerUSGallon: return _value / 0.1335264711843; - case MassConcentrationUnit.PicogramPerDeciliter: return (_value / 1e-1) * 1e-12d; - case MassConcentrationUnit.PicogramPerLiter: return (_value) * 1e-12d; - case MassConcentrationUnit.PicogramPerMicroliter: return (_value / 1e-6) * 1e-12d; - case MassConcentrationUnit.PicogramPerMilliliter: return (_value / 1e-3) * 1e-12d; - case MassConcentrationUnit.PoundPerCubicFoot: return _value / 0.062427961; - case MassConcentrationUnit.PoundPerCubicInch: return _value / 3.6127298147753e-5; - case MassConcentrationUnit.PoundPerImperialGallon: return _value * 9.9776398e1; - case MassConcentrationUnit.PoundPerUSGallon: return _value * 1.19826427e2; - case MassConcentrationUnit.SlugPerCubicFoot: return _value * 515.378818; - case MassConcentrationUnit.TonnePerCubicCentimeter: return _value / 1e-9; - case MassConcentrationUnit.TonnePerCubicMeter: return _value / 0.001; - case MassConcentrationUnit.TonnePerCubicMillimeter: return _value / 1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassConcentrationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassConcentrationUnit.CentigramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-2d; - case MassConcentrationUnit.CentigramPerLiter: return (baseUnitValue) / 1e-2d; - case MassConcentrationUnit.CentigramPerMicroliter: return (baseUnitValue * 1e-6) / 1e-2d; - case MassConcentrationUnit.CentigramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-2d; - case MassConcentrationUnit.DecigramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-1d; - case MassConcentrationUnit.DecigramPerLiter: return (baseUnitValue) / 1e-1d; - case MassConcentrationUnit.DecigramPerMicroliter: return (baseUnitValue * 1e-6) / 1e-1d; - case MassConcentrationUnit.DecigramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-1d; - case MassConcentrationUnit.GramPerCubicCentimeter: return baseUnitValue * 1e-3; - case MassConcentrationUnit.GramPerCubicMeter: return baseUnitValue * 1e3; - case MassConcentrationUnit.GramPerCubicMillimeter: return baseUnitValue * 1e-6; - case MassConcentrationUnit.GramPerDeciliter: return baseUnitValue * 1e-1; - case MassConcentrationUnit.GramPerLiter: return baseUnitValue; - case MassConcentrationUnit.GramPerMicroliter: return baseUnitValue * 1e-6; - case MassConcentrationUnit.GramPerMilliliter: return baseUnitValue * 1e-3; - case MassConcentrationUnit.KilogramPerCubicCentimeter: return (baseUnitValue * 1e-3) / 1e3d; - case MassConcentrationUnit.KilogramPerCubicMeter: return (baseUnitValue * 1e3) / 1e3d; - case MassConcentrationUnit.KilogramPerCubicMillimeter: return (baseUnitValue * 1e-6) / 1e3d; - case MassConcentrationUnit.KilogramPerLiter: return (baseUnitValue) / 1e3d; - case MassConcentrationUnit.KilopoundPerCubicFoot: return (baseUnitValue * 0.062427961) / 1e3d; - case MassConcentrationUnit.KilopoundPerCubicInch: return (baseUnitValue * 3.6127298147753e-5) / 1e3d; - case MassConcentrationUnit.MicrogramPerCubicMeter: return (baseUnitValue * 1e3) / 1e-6d; - case MassConcentrationUnit.MicrogramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-6d; - case MassConcentrationUnit.MicrogramPerLiter: return (baseUnitValue) / 1e-6d; - case MassConcentrationUnit.MicrogramPerMicroliter: return (baseUnitValue * 1e-6) / 1e-6d; - case MassConcentrationUnit.MicrogramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-6d; - case MassConcentrationUnit.MilligramPerCubicMeter: return (baseUnitValue * 1e3) / 1e-3d; - case MassConcentrationUnit.MilligramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-3d; - case MassConcentrationUnit.MilligramPerLiter: return (baseUnitValue) / 1e-3d; - case MassConcentrationUnit.MilligramPerMicroliter: return (baseUnitValue * 1e-6) / 1e-3d; - case MassConcentrationUnit.MilligramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-3d; - case MassConcentrationUnit.NanogramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-9d; - case MassConcentrationUnit.NanogramPerLiter: return (baseUnitValue) / 1e-9d; - case MassConcentrationUnit.NanogramPerMicroliter: return (baseUnitValue * 1e-6) / 1e-9d; - case MassConcentrationUnit.NanogramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-9d; - case MassConcentrationUnit.OuncePerImperialGallon: return baseUnitValue * 0.1603586720609; - case MassConcentrationUnit.OuncePerUSGallon: return baseUnitValue * 0.1335264711843; - case MassConcentrationUnit.PicogramPerDeciliter: return (baseUnitValue * 1e-1) / 1e-12d; - case MassConcentrationUnit.PicogramPerLiter: return (baseUnitValue) / 1e-12d; - case MassConcentrationUnit.PicogramPerMicroliter: return (baseUnitValue * 1e-6) / 1e-12d; - case MassConcentrationUnit.PicogramPerMilliliter: return (baseUnitValue * 1e-3) / 1e-12d; - case MassConcentrationUnit.PoundPerCubicFoot: return baseUnitValue * 0.062427961; - case MassConcentrationUnit.PoundPerCubicInch: return baseUnitValue * 3.6127298147753e-5; - case MassConcentrationUnit.PoundPerImperialGallon: return baseUnitValue / 9.9776398e1; - case MassConcentrationUnit.PoundPerUSGallon: return baseUnitValue / 1.19826427e2; - case MassConcentrationUnit.SlugPerCubicFoot: return baseUnitValue * 0.00194032033; - case MassConcentrationUnit.TonnePerCubicCentimeter: return baseUnitValue * 1e-9; - case MassConcentrationUnit.TonnePerCubicMeter: return baseUnitValue * 0.001; - case MassConcentrationUnit.TonnePerCubicMillimeter: return baseUnitValue * 1e-12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.g.cs deleted file mode 100644 index a6c4ac368d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlow.g.cs +++ /dev/null @@ -1,1203 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassFlow : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFlowUnit? _unit; - - static MassFlow() - { - BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); - BaseUnit = MassFlowUnit.GramPerSecond; - MaxValue = new MassFlow(double.MaxValue, BaseUnit); - MinValue = new MassFlow(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassFlow; - Units = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); - Zero = new MassFlow(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MassFlow, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit GramPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MassFlow() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MassFlow(double value, MassFlowUnit unit) - { - if (unit == MassFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. - /// - public static MassFlowUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MassFlow - /// - public static MassFlow MaxValue { get; } - - /// - /// Represents the smallest possible value of MassFlow - /// - public static MassFlow MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MassFlow quantity. - /// - public static MassFlowUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. - /// - public static MassFlow Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MassFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFlow.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerDay => As(MassFlowUnit.CentigramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecagramsPerDay => As(MassFlowUnit.DecagramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerDay => As(MassFlowUnit.DecigramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerDay => As(MassFlowUnit.GramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerHour => As(MassFlowUnit.GramPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double HectogramsPerDay => As(MassFlowUnit.HectogramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerDay => As(MassFlowUnit.KilogramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegagramsPerDay => As(MassFlowUnit.MegagramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsPerDay => As(MassFlowUnit.MegapoundPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsPerSecond => As(MassFlowUnit.MegapoundPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerDay => As(MassFlowUnit.MicrogramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerDay => As(MassFlowUnit.MilligramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerDay => As(MassFlowUnit.NanogramPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerDay => As(MassFlowUnit.PoundPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerSecond => As(MassFlowUnit.PoundPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MassFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromCentigramsPerDay(double centigramsperday) - { - double value = (double) centigramsperday; - return new MassFlow(value, MassFlowUnit.CentigramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromCentigramsPerSecond(double centigramspersecond) - { - double value = (double) centigramspersecond; - return new MassFlow(value, MassFlowUnit.CentigramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecagramsPerDay(double decagramsperday) - { - double value = (double) decagramsperday; - return new MassFlow(value, MassFlowUnit.DecagramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecagramsPerSecond(double decagramspersecond) - { - double value = (double) decagramspersecond; - return new MassFlow(value, MassFlowUnit.DecagramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecigramsPerDay(double decigramsperday) - { - double value = (double) decigramsperday; - return new MassFlow(value, MassFlowUnit.DecigramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromDecigramsPerSecond(double decigramspersecond) - { - double value = (double) decigramspersecond; - return new MassFlow(value, MassFlowUnit.DecigramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromGramsPerDay(double gramsperday) - { - double value = (double) gramsperday; - return new MassFlow(value, MassFlowUnit.GramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromGramsPerHour(double gramsperhour) - { - double value = (double) gramsperhour; - return new MassFlow(value, MassFlowUnit.GramPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromGramsPerSecond(double gramspersecond) - { - double value = (double) gramspersecond; - return new MassFlow(value, MassFlowUnit.GramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromHectogramsPerDay(double hectogramsperday) - { - double value = (double) hectogramsperday; - return new MassFlow(value, MassFlowUnit.HectogramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromHectogramsPerSecond(double hectogramspersecond) - { - double value = (double) hectogramspersecond; - return new MassFlow(value, MassFlowUnit.HectogramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerDay(double kilogramsperday) - { - double value = (double) kilogramsperday; - return new MassFlow(value, MassFlowUnit.KilogramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerHour(double kilogramsperhour) - { - double value = (double) kilogramsperhour; - return new MassFlow(value, MassFlowUnit.KilogramPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerMinute(double kilogramsperminute) - { - double value = (double) kilogramsperminute; - return new MassFlow(value, MassFlowUnit.KilogramPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromKilogramsPerSecond(double kilogramspersecond) - { - double value = (double) kilogramspersecond; - return new MassFlow(value, MassFlowUnit.KilogramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegagramsPerDay(double megagramsperday) - { - double value = (double) megagramsperday; - return new MassFlow(value, MassFlowUnit.MegagramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerDay(double megapoundsperday) - { - double value = (double) megapoundsperday; - return new MassFlow(value, MassFlowUnit.MegapoundPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerHour(double megapoundsperhour) - { - double value = (double) megapoundsperhour; - return new MassFlow(value, MassFlowUnit.MegapoundPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerMinute(double megapoundsperminute) - { - double value = (double) megapoundsperminute; - return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMegapoundsPerSecond(double megapoundspersecond) - { - double value = (double) megapoundspersecond; - return new MassFlow(value, MassFlowUnit.MegapoundPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMicrogramsPerDay(double microgramsperday) - { - double value = (double) microgramsperday; - return new MassFlow(value, MassFlowUnit.MicrogramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMicrogramsPerSecond(double microgramspersecond) - { - double value = (double) microgramspersecond; - return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMilligramsPerDay(double milligramsperday) - { - double value = (double) milligramsperday; - return new MassFlow(value, MassFlowUnit.MilligramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromMilligramsPerSecond(double milligramspersecond) - { - double value = (double) milligramspersecond; - return new MassFlow(value, MassFlowUnit.MilligramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromNanogramsPerDay(double nanogramsperday) - { - double value = (double) nanogramsperday; - return new MassFlow(value, MassFlowUnit.NanogramPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromNanogramsPerSecond(double nanogramspersecond) - { - double value = (double) nanogramspersecond; - return new MassFlow(value, MassFlowUnit.NanogramPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerDay(double poundsperday) - { - double value = (double) poundsperday; - return new MassFlow(value, MassFlowUnit.PoundPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerHour(double poundsperhour) - { - double value = (double) poundsperhour; - return new MassFlow(value, MassFlowUnit.PoundPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerMinute(double poundsperminute) - { - double value = (double) poundsperminute; - return new MassFlow(value, MassFlowUnit.PoundPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromPoundsPerSecond(double poundspersecond) - { - double value = (double) poundspersecond; - return new MassFlow(value, MassFlowUnit.PoundPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromShortTonsPerHour(double shorttonsperhour) - { - double value = (double) shorttonsperhour; - return new MassFlow(value, MassFlowUnit.ShortTonPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromTonnesPerDay(double tonnesperday) - { - double value = (double) tonnesperday; - return new MassFlow(value, MassFlowUnit.TonnePerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlow FromTonnesPerHour(double tonnesperhour) - { - double value = (double) tonnesperhour; - return new MassFlow(value, MassFlowUnit.TonnePerHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFlow unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFlow From(double value, MassFlowUnit fromUnit) - { - return new MassFlow((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFlow Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassFlow Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFlow result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MassFlow result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFlowUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MassFlowUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MassFlowUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassFlow objMassFlow)) throw new ArgumentException("Expected type MassFlow.", nameof(obj)); - - return CompareTo(objMassFlow); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MassFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassFlow objMassFlow)) - return false; - - return Equals(objMassFlow); - } - - public bool Equals(MassFlow other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MassFlowUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFlowUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFlow to another MassFlow with the unit representation . - /// - /// A MassFlow with the specified unit. - public MassFlow ToUnit(MassFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassFlowUnit.CentigramPerDay: return (_value / 86400) * 1e-2d; - case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; - case MassFlowUnit.DecagramPerDay: return (_value / 86400) * 1e1d; - case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; - case MassFlowUnit.DecigramPerDay: return (_value / 86400) * 1e-1d; - case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; - case MassFlowUnit.GramPerDay: return _value / 86400; - case MassFlowUnit.GramPerHour: return _value / 3600; - case MassFlowUnit.GramPerSecond: return _value; - case MassFlowUnit.HectogramPerDay: return (_value / 86400) * 1e2d; - case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; - case MassFlowUnit.KilogramPerDay: return (_value / 86400) * 1e3d; - case MassFlowUnit.KilogramPerHour: return _value / 3.6; - case MassFlowUnit.KilogramPerMinute: return _value / 0.06; - case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; - case MassFlowUnit.MegagramPerDay: return (_value / 86400) * 1e6d; - case MassFlowUnit.MegapoundPerDay: return (_value / 190.47936) * 1e6d; - case MassFlowUnit.MegapoundPerHour: return (_value / 7.93664) * 1e6d; - case MassFlowUnit.MegapoundPerMinute: return (_value / 0.132277) * 1e6d; - case MassFlowUnit.MegapoundPerSecond: return (_value * 453.59237) * 1e6d; - case MassFlowUnit.MicrogramPerDay: return (_value / 86400) * 1e-6d; - case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; - case MassFlowUnit.MilligramPerDay: return (_value / 86400) * 1e-3d; - case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; - case MassFlowUnit.NanogramPerDay: return (_value / 86400) * 1e-9d; - case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; - case MassFlowUnit.PoundPerDay: return _value / 190.47936; - case MassFlowUnit.PoundPerHour: return _value / 7.93664; - case MassFlowUnit.PoundPerMinute: return _value / 0.132277; - case MassFlowUnit.PoundPerSecond: return _value * 453.59237; - case MassFlowUnit.ShortTonPerHour: return _value * 251.9957611; - case MassFlowUnit.TonnePerDay: return _value / 0.0864000; - case MassFlowUnit.TonnePerHour: return 1000 * _value / 3.6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFlowUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFlowUnit.CentigramPerDay: return (baseUnitValue * 86400) / 1e-2d; - case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; - case MassFlowUnit.DecagramPerDay: return (baseUnitValue * 86400) / 1e1d; - case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; - case MassFlowUnit.DecigramPerDay: return (baseUnitValue * 86400) / 1e-1d; - case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; - case MassFlowUnit.GramPerDay: return baseUnitValue * 86400; - case MassFlowUnit.GramPerHour: return baseUnitValue * 3600; - case MassFlowUnit.GramPerSecond: return baseUnitValue; - case MassFlowUnit.HectogramPerDay: return (baseUnitValue * 86400) / 1e2d; - case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; - case MassFlowUnit.KilogramPerDay: return (baseUnitValue * 86400) / 1e3d; - case MassFlowUnit.KilogramPerHour: return baseUnitValue * 3.6; - case MassFlowUnit.KilogramPerMinute: return baseUnitValue * 0.06; - case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; - case MassFlowUnit.MegagramPerDay: return (baseUnitValue * 86400) / 1e6d; - case MassFlowUnit.MegapoundPerDay: return (baseUnitValue * 190.47936) / 1e6d; - case MassFlowUnit.MegapoundPerHour: return (baseUnitValue * 7.93664) / 1e6d; - case MassFlowUnit.MegapoundPerMinute: return (baseUnitValue * 0.132277) / 1e6d; - case MassFlowUnit.MegapoundPerSecond: return (baseUnitValue / 453.59237) / 1e6d; - case MassFlowUnit.MicrogramPerDay: return (baseUnitValue * 86400) / 1e-6d; - case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; - case MassFlowUnit.MilligramPerDay: return (baseUnitValue * 86400) / 1e-3d; - case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; - case MassFlowUnit.NanogramPerDay: return (baseUnitValue * 86400) / 1e-9d; - case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; - case MassFlowUnit.PoundPerDay: return baseUnitValue * 190.47936; - case MassFlowUnit.PoundPerHour: return baseUnitValue * 7.93664; - case MassFlowUnit.PoundPerMinute: return baseUnitValue * 0.132277; - case MassFlowUnit.PoundPerSecond: return baseUnitValue / 453.59237; - case MassFlowUnit.ShortTonPerHour: return baseUnitValue / 251.9957611; - case MassFlowUnit.TonnePerDay: return baseUnitValue * 0.0864000; - case MassFlowUnit.TonnePerHour: return baseUnitValue * 3.6 / 1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.g.cs deleted file mode 100644 index 38a1f34f9d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFlux.g.cs +++ /dev/null @@ -1,802 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Mass flux is the mass flow rate per unit area. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassFlux : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFluxUnit? _unit; - - static MassFlux() - { - BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); - BaseUnit = MassFluxUnit.KilogramPerSecondPerSquareMeter; - MaxValue = new MassFlux(double.MaxValue, BaseUnit); - MinValue = new MassFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassFlux; - Units = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); - Zero = new MassFlux(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MassFlux, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MassFlux() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MassFlux(double value, MassFluxUnit unit) - { - if (unit == MassFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. - /// - public static MassFluxUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MassFlux - /// - public static MassFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of MassFlux - /// - public static MassFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MassFlux quantity. - /// - public static MassFluxUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. - /// - public static MassFlux Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MassFlux.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFlux.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerHourPerSquareCentimeter => As(MassFluxUnit.GramPerHourPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerHourPerSquareMeter => As(MassFluxUnit.GramPerHourPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerHourPerSquareMillimeter => As(MassFluxUnit.GramPerHourPerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerSecondPerSquareCentimeter => As(MassFluxUnit.GramPerSecondPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerSecondPerSquareMillimeter => As(MassFluxUnit.GramPerSecondPerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerHourPerSquareCentimeter => As(MassFluxUnit.KilogramPerHourPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerHourPerSquareMeter => As(MassFluxUnit.KilogramPerHourPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerHourPerSquareMillimeter => As(MassFluxUnit.KilogramPerHourPerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerSecondPerSquareCentimeter => As(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerSecondPerSquareMillimeter => As(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); - - #endregion - - #region Static Methods - - 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⁻²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MassFluxUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerHourPerSquareCentimeter(double gramsperhourpersquarecentimeter) - { - double value = (double) gramsperhourpersquarecentimeter; - return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerHourPerSquareMeter(double gramsperhourpersquaremeter) - { - double value = (double) gramsperhourpersquaremeter; - return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerHourPerSquareMillimeter(double gramsperhourpersquaremillimeter) - { - double value = (double) gramsperhourpersquaremillimeter; - return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerSecondPerSquareCentimeter(double gramspersecondpersquarecentimeter) - { - double value = (double) gramspersecondpersquarecentimeter; - return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerSecondPerSquareMeter(double gramspersecondpersquaremeter) - { - double value = (double) gramspersecondpersquaremeter; - return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromGramsPerSecondPerSquareMillimeter(double gramspersecondpersquaremillimeter) - { - double value = (double) gramspersecondpersquaremillimeter; - return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerHourPerSquareCentimeter(double kilogramsperhourpersquarecentimeter) - { - double value = (double) kilogramsperhourpersquarecentimeter; - return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerHourPerSquareMeter(double kilogramsperhourpersquaremeter) - { - double value = (double) kilogramsperhourpersquaremeter; - return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerHourPerSquareMillimeter(double kilogramsperhourpersquaremillimeter) - { - double value = (double) kilogramsperhourpersquaremillimeter; - return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(double kilogramspersecondpersquarecentimeter) - { - double value = (double) kilogramspersecondpersquarecentimeter; - return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerSecondPerSquareMeter(double kilogramspersecondpersquaremeter) - { - double value = (double) kilogramspersecondpersquaremeter; - return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(double kilogramspersecondpersquaremillimeter) - { - double value = (double) kilogramspersecondpersquaremillimeter; - return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFlux unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFlux From(double value, MassFluxUnit fromUnit) - { - return new MassFlux((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFlux Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassFlux Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFlux result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MassFlux result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFluxUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MassFluxUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MassFluxUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassFlux objMassFlux)) throw new ArgumentException("Expected type MassFlux.", nameof(obj)); - - return CompareTo(objMassFlux); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MassFlux other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassFlux objMassFlux)) - return false; - - return Equals(objMassFlux); - } - - public bool Equals(MassFlux other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MassFluxUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFluxUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFlux to another MassFlux with the unit representation . - /// - /// A MassFlux with the specified unit. - public MassFlux ToUnit(MassFluxUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFlux(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassFluxUnit.GramPerHourPerSquareCentimeter: return _value / 3.6e2; - case MassFluxUnit.GramPerHourPerSquareMeter: return _value / 3.6e6; - case MassFluxUnit.GramPerHourPerSquareMillimeter: return _value / 3.6e0; - case MassFluxUnit.GramPerSecondPerSquareCentimeter: return _value / 1e-1; - case MassFluxUnit.GramPerSecondPerSquareMeter: return _value / 1e3; - case MassFluxUnit.GramPerSecondPerSquareMillimeter: return _value / 1e-3; - case MassFluxUnit.KilogramPerHourPerSquareCentimeter: return (_value / 3.6e2) * 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMeter: return (_value / 3.6e6) * 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMillimeter: return (_value / 3.6e0) * 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareCentimeter: return (_value / 1e-1) * 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value / 1e3) * 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMillimeter: return (_value / 1e-3) * 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFluxUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFluxUnit.GramPerHourPerSquareCentimeter: return baseUnitValue * 3.6e2; - case MassFluxUnit.GramPerHourPerSquareMeter: return baseUnitValue * 3.6e6; - case MassFluxUnit.GramPerHourPerSquareMillimeter: return baseUnitValue * 3.6e0; - case MassFluxUnit.GramPerSecondPerSquareCentimeter: return baseUnitValue * 1e-1; - case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue * 1e3; - case MassFluxUnit.GramPerSecondPerSquareMillimeter: return baseUnitValue * 1e-3; - case MassFluxUnit.KilogramPerHourPerSquareCentimeter: return (baseUnitValue * 3.6e2) / 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMeter: return (baseUnitValue * 3.6e6) / 1e3d; - case MassFluxUnit.KilogramPerHourPerSquareMillimeter: return (baseUnitValue * 3.6e0) / 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareCentimeter: return (baseUnitValue * 1e-1) / 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue * 1e3) / 1e3d; - case MassFluxUnit.KilogramPerSecondPerSquareMillimeter: return (baseUnitValue * 1e-3) / 1e3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFraction.g.cs deleted file mode 100644 index 69ad1d01af..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassFraction.g.cs +++ /dev/null @@ -1,1033 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The mass fraction is defined as the mass of a constituent divided by the total mass of the mixture. - /// - /// - /// https://en.wikipedia.org/wiki/Mass_fraction_(chemistry) - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassFraction : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassFractionUnit? _unit; - - static MassFraction() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = MassFractionUnit.DecimalFraction; - MaxValue = new MassFraction(double.MaxValue, BaseUnit); - MinValue = new MassFraction(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassFraction; - Units = Enum.GetValues(typeof(MassFractionUnit)).Cast().Except(new MassFractionUnit[]{ MassFractionUnit.Undefined }).ToArray(); - Zero = new MassFraction(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MassFraction, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DecimalFraction. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MassFraction() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MassFraction(double value, MassFractionUnit unit) - { - if (unit == MassFractionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MassFraction, which is DecimalFraction. All conversions go via this value. - /// - public static MassFractionUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MassFraction - /// - public static MassFraction MaxValue { get; } - - /// - /// Represents the smallest possible value of MassFraction - /// - public static MassFraction MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MassFraction quantity. - /// - public static MassFractionUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. - /// - public static MassFraction Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassFractionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MassFraction.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassFraction.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerGram => As(MassFractionUnit.CentigramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerKilogram => As(MassFractionUnit.CentigramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double DecagramsPerGram => As(MassFractionUnit.DecagramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double DecagramsPerKilogram => As(MassFractionUnit.DecagramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerGram => As(MassFractionUnit.DecigramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerKilogram => As(MassFractionUnit.DecigramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimalFractions => As(MassFractionUnit.DecimalFraction); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerGram => As(MassFractionUnit.GramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerKilogram => As(MassFractionUnit.GramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double HectogramsPerGram => As(MassFractionUnit.HectogramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double HectogramsPerKilogram => As(MassFractionUnit.HectogramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerGram => As(MassFractionUnit.KilogramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerKilogram => As(MassFractionUnit.KilogramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerGram => As(MassFractionUnit.MicrogramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerKilogram => As(MassFractionUnit.MicrogramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerGram => As(MassFractionUnit.MilligramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerKilogram => As(MassFractionUnit.MilligramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerGram => As(MassFractionUnit.NanogramPerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerKilogram => As(MassFractionUnit.NanogramPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerBillion => As(MassFractionUnit.PartPerBillion); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerMillion => As(MassFractionUnit.PartPerMillion); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerThousand => As(MassFractionUnit.PartPerThousand); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerTrillion => As(MassFractionUnit.PartPerTrillion); - - /// - /// Gets a value of this quantity converted into - /// - public double Percent => As(MassFractionUnit.Percent); - - #endregion - - #region Static Methods - - 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)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MassFractionUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MassFractionUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromCentigramsPerGram(double centigramspergram) - { - double value = (double) centigramspergram; - return new MassFraction(value, MassFractionUnit.CentigramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromCentigramsPerKilogram(double centigramsperkilogram) - { - double value = (double) centigramsperkilogram; - return new MassFraction(value, MassFractionUnit.CentigramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromDecagramsPerGram(double decagramspergram) - { - double value = (double) decagramspergram; - return new MassFraction(value, MassFractionUnit.DecagramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromDecagramsPerKilogram(double decagramsperkilogram) - { - double value = (double) decagramsperkilogram; - return new MassFraction(value, MassFractionUnit.DecagramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromDecigramsPerGram(double decigramspergram) - { - double value = (double) decigramspergram; - return new MassFraction(value, MassFractionUnit.DecigramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromDecigramsPerKilogram(double decigramsperkilogram) - { - double value = (double) decigramsperkilogram; - return new MassFraction(value, MassFractionUnit.DecigramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromDecimalFractions(double decimalfractions) - { - double value = (double) decimalfractions; - return new MassFraction(value, MassFractionUnit.DecimalFraction); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromGramsPerGram(double gramspergram) - { - double value = (double) gramspergram; - return new MassFraction(value, MassFractionUnit.GramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromGramsPerKilogram(double gramsperkilogram) - { - double value = (double) gramsperkilogram; - return new MassFraction(value, MassFractionUnit.GramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromHectogramsPerGram(double hectogramspergram) - { - double value = (double) hectogramspergram; - return new MassFraction(value, MassFractionUnit.HectogramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromHectogramsPerKilogram(double hectogramsperkilogram) - { - double value = (double) hectogramsperkilogram; - return new MassFraction(value, MassFractionUnit.HectogramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromKilogramsPerGram(double kilogramspergram) - { - double value = (double) kilogramspergram; - return new MassFraction(value, MassFractionUnit.KilogramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromKilogramsPerKilogram(double kilogramsperkilogram) - { - double value = (double) kilogramsperkilogram; - return new MassFraction(value, MassFractionUnit.KilogramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromMicrogramsPerGram(double microgramspergram) - { - double value = (double) microgramspergram; - return new MassFraction(value, MassFractionUnit.MicrogramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromMicrogramsPerKilogram(double microgramsperkilogram) - { - double value = (double) microgramsperkilogram; - return new MassFraction(value, MassFractionUnit.MicrogramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromMilligramsPerGram(double milligramspergram) - { - double value = (double) milligramspergram; - return new MassFraction(value, MassFractionUnit.MilligramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromMilligramsPerKilogram(double milligramsperkilogram) - { - double value = (double) milligramsperkilogram; - return new MassFraction(value, MassFractionUnit.MilligramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromNanogramsPerGram(double nanogramspergram) - { - double value = (double) nanogramspergram; - return new MassFraction(value, MassFractionUnit.NanogramPerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromNanogramsPerKilogram(double nanogramsperkilogram) - { - double value = (double) nanogramsperkilogram; - return new MassFraction(value, MassFractionUnit.NanogramPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromPartsPerBillion(double partsperbillion) - { - double value = (double) partsperbillion; - return new MassFraction(value, MassFractionUnit.PartPerBillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromPartsPerMillion(double partspermillion) - { - double value = (double) partspermillion; - return new MassFraction(value, MassFractionUnit.PartPerMillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromPartsPerThousand(double partsperthousand) - { - double value = (double) partsperthousand; - return new MassFraction(value, MassFractionUnit.PartPerThousand); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromPartsPerTrillion(double partspertrillion) - { - double value = (double) partspertrillion; - return new MassFraction(value, MassFractionUnit.PartPerTrillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassFraction FromPercent(double percent) - { - double value = (double) percent; - return new MassFraction(value, MassFractionUnit.Percent); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassFraction unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassFraction From(double value, MassFractionUnit fromUnit) - { - return new MassFraction((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassFraction Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassFraction Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassFraction result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MassFraction result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassFractionUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassFractionUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MassFractionUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MassFractionUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassFraction objMassFraction)) throw new ArgumentException("Expected type MassFraction.", nameof(obj)); - - return CompareTo(objMassFraction); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MassFraction other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassFraction objMassFraction)) - return false; - - return Equals(objMassFraction); - } - - public bool Equals(MassFraction other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassFraction within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFraction. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MassFractionUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFractionUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassFraction to another MassFraction with the unit representation . - /// - /// A MassFraction with the specified unit. - public MassFraction ToUnit(MassFractionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassFraction(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassFractionUnit.CentigramPerGram: return (_value) * 1e-2d; - case MassFractionUnit.CentigramPerKilogram: return (_value / 1e3) * 1e-2d; - case MassFractionUnit.DecagramPerGram: return (_value) * 1e1d; - case MassFractionUnit.DecagramPerKilogram: return (_value / 1e3) * 1e1d; - case MassFractionUnit.DecigramPerGram: return (_value) * 1e-1d; - case MassFractionUnit.DecigramPerKilogram: return (_value / 1e3) * 1e-1d; - case MassFractionUnit.DecimalFraction: return _value; - case MassFractionUnit.GramPerGram: return _value; - case MassFractionUnit.GramPerKilogram: return _value / 1e3; - case MassFractionUnit.HectogramPerGram: return (_value) * 1e2d; - case MassFractionUnit.HectogramPerKilogram: return (_value / 1e3) * 1e2d; - case MassFractionUnit.KilogramPerGram: return (_value) * 1e3d; - case MassFractionUnit.KilogramPerKilogram: return (_value / 1e3) * 1e3d; - case MassFractionUnit.MicrogramPerGram: return (_value) * 1e-6d; - case MassFractionUnit.MicrogramPerKilogram: return (_value / 1e3) * 1e-6d; - case MassFractionUnit.MilligramPerGram: return (_value) * 1e-3d; - case MassFractionUnit.MilligramPerKilogram: return (_value / 1e3) * 1e-3d; - case MassFractionUnit.NanogramPerGram: return (_value) * 1e-9d; - case MassFractionUnit.NanogramPerKilogram: return (_value / 1e3) * 1e-9d; - case MassFractionUnit.PartPerBillion: return _value / 1e9; - case MassFractionUnit.PartPerMillion: return _value / 1e6; - case MassFractionUnit.PartPerThousand: return _value / 1e3; - case MassFractionUnit.PartPerTrillion: return _value / 1e12; - case MassFractionUnit.Percent: return _value / 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassFractionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassFractionUnit.CentigramPerGram: return (baseUnitValue) / 1e-2d; - case MassFractionUnit.CentigramPerKilogram: return (baseUnitValue * 1e3) / 1e-2d; - case MassFractionUnit.DecagramPerGram: return (baseUnitValue) / 1e1d; - case MassFractionUnit.DecagramPerKilogram: return (baseUnitValue * 1e3) / 1e1d; - case MassFractionUnit.DecigramPerGram: return (baseUnitValue) / 1e-1d; - case MassFractionUnit.DecigramPerKilogram: return (baseUnitValue * 1e3) / 1e-1d; - case MassFractionUnit.DecimalFraction: return baseUnitValue; - case MassFractionUnit.GramPerGram: return baseUnitValue; - case MassFractionUnit.GramPerKilogram: return baseUnitValue * 1e3; - case MassFractionUnit.HectogramPerGram: return (baseUnitValue) / 1e2d; - case MassFractionUnit.HectogramPerKilogram: return (baseUnitValue * 1e3) / 1e2d; - case MassFractionUnit.KilogramPerGram: return (baseUnitValue) / 1e3d; - case MassFractionUnit.KilogramPerKilogram: return (baseUnitValue * 1e3) / 1e3d; - case MassFractionUnit.MicrogramPerGram: return (baseUnitValue) / 1e-6d; - case MassFractionUnit.MicrogramPerKilogram: return (baseUnitValue * 1e3) / 1e-6d; - case MassFractionUnit.MilligramPerGram: return (baseUnitValue) / 1e-3d; - case MassFractionUnit.MilligramPerKilogram: return (baseUnitValue * 1e3) / 1e-3d; - case MassFractionUnit.NanogramPerGram: return (baseUnitValue) / 1e-9d; - case MassFractionUnit.NanogramPerKilogram: return (baseUnitValue * 1e3) / 1e-9d; - case MassFractionUnit.PartPerBillion: return baseUnitValue * 1e9; - case MassFractionUnit.PartPerMillion: return baseUnitValue * 1e6; - case MassFractionUnit.PartPerThousand: return baseUnitValue * 1e3; - case MassFractionUnit.PartPerTrillion: return baseUnitValue * 1e12; - case MassFractionUnit.Percent: return baseUnitValue * 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.g.cs deleted file mode 100644 index a2b16e4db0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ /dev/null @@ -1,1106 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A property of body reflects how its mass is distributed with regard to an axis. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MassMomentOfInertia : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MassMomentOfInertiaUnit? _unit; - - static MassMomentOfInertia() - { - BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); - BaseUnit = MassMomentOfInertiaUnit.KilogramSquareMeter; - MaxValue = new MassMomentOfInertia(double.MaxValue, BaseUnit); - MinValue = new MassMomentOfInertia(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassMomentOfInertia; - Units = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); - Zero = new MassMomentOfInertia(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MassMomentOfInertia, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MassMomentOfInertia() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MassMomentOfInertia(double value, MassMomentOfInertiaUnit unit) - { - if (unit == MassMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. - /// - public static MassMomentOfInertiaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MassMomentOfInertia - /// - public static MassMomentOfInertia MaxValue { get; } - - /// - /// Represents the smallest possible value of MassMomentOfInertia - /// - public static MassMomentOfInertia MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MassMomentOfInertia quantity. - /// - public static MassMomentOfInertiaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. - /// - public static MassMomentOfInertia Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MassMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MassMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareCentimeters(double gramsquarecentimeters) - { - double value = (double) gramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareDecimeters(double gramsquaredecimeters) - { - double value = (double) gramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareMeters(double gramsquaremeters) - { - double value = (double) gramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromGramSquareMillimeters(double gramsquaremillimeters) - { - double value = (double) gramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareCentimeters(double kilogramsquarecentimeters) - { - double value = (double) kilogramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareDecimeters(double kilogramsquaredecimeters) - { - double value = (double) kilogramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareMeters(double kilogramsquaremeters) - { - double value = (double) kilogramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilogramSquareMillimeters(double kilogramsquaremillimeters) - { - double value = (double) kilogramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareCentimeters(double kilotonnesquarecentimeters) - { - double value = (double) kilotonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareDecimeters(double kilotonnesquaredecimeters) - { - double value = (double) kilotonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareMeters(double kilotonnesquaremeters) - { - double value = (double) kilotonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromKilotonneSquareMilimeters(double kilotonnesquaremilimeters) - { - double value = (double) kilotonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareCentimeters(double megatonnesquarecentimeters) - { - double value = (double) megatonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareDecimeters(double megatonnesquaredecimeters) - { - double value = (double) megatonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareMeters(double megatonnesquaremeters) - { - double value = (double) megatonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMegatonneSquareMilimeters(double megatonnesquaremilimeters) - { - double value = (double) megatonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareCentimeters(double milligramsquarecentimeters) - { - double value = (double) milligramsquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareDecimeters(double milligramsquaredecimeters) - { - double value = (double) milligramsquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareMeters(double milligramsquaremeters) - { - double value = (double) milligramsquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromMilligramSquareMillimeters(double milligramsquaremillimeters) - { - double value = (double) milligramsquaremillimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromPoundSquareFeet(double poundsquarefeet) - { - double value = (double) poundsquarefeet; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromPoundSquareInches(double poundsquareinches) - { - double value = (double) poundsquareinches; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromSlugSquareFeet(double slugsquarefeet) - { - double value = (double) slugsquarefeet; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromSlugSquareInches(double slugsquareinches) - { - double value = (double) slugsquareinches; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareCentimeters(double tonnesquarecentimeters) - { - double value = (double) tonnesquarecentimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareDecimeters(double tonnesquaredecimeters) - { - double value = (double) tonnesquaredecimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareMeters(double tonnesquaremeters) - { - double value = (double) tonnesquaremeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MassMomentOfInertia FromTonneSquareMilimeters(double tonnesquaremilimeters) - { - double value = (double) tonnesquaremilimeters; - return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MassMomentOfInertia unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fromUnit) - { - return new MassMomentOfInertia((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MassMomentOfInertia Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassMomentOfInertia Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MassMomentOfInertia result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MassMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MassMomentOfInertiaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassMomentOfInertia objMassMomentOfInertia)) throw new ArgumentException("Expected type MassMomentOfInertia.", nameof(obj)); - - return CompareTo(objMassMomentOfInertia); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MassMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassMomentOfInertia objMassMomentOfInertia)) - return false; - - return Equals(objMassMomentOfInertia); - } - - public bool Equals(MassMomentOfInertia other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MassMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassMomentOfInertia. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MassMomentOfInertiaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassMomentOfInertiaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . - /// - /// A MassMomentOfInertia with the specified unit. - public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MassMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return _value / 1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return _value / 1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return _value / 1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return _value / 1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (_value / 1e7) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (_value / 1e5) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (_value / 1e3) * 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (_value / 1e9) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (_value / 1e1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (_value / 1e-1) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (_value / 1e-3) * 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (_value / 1e3) * 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (_value / 1e1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (_value / 1e-1) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (_value / 1e-3) * 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (_value / 1e3) * 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (_value / 1e7) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (_value / 1e5) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (_value / 1e3) * 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (_value / 1e9) * 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return _value * 4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return _value * 2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return _value * 1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return _value * 9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return _value / 1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return _value / 1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return _value / 1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return _value / 1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MassMomentOfInertiaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: return baseUnitValue * 1e7; - case MassMomentOfInertiaUnit.GramSquareDecimeter: return baseUnitValue * 1e5; - case MassMomentOfInertiaUnit.GramSquareMeter: return baseUnitValue * 1e3; - case MassMomentOfInertiaUnit.GramSquareMillimeter: return baseUnitValue * 1e9; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (baseUnitValue * 1e7) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (baseUnitValue * 1e5) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMeter: return (baseUnitValue * 1e3) / 1e3d; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (baseUnitValue * 1e9) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (baseUnitValue * 1e1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (baseUnitValue * 1e-1) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (baseUnitValue * 1e-3) / 1e3d; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (baseUnitValue * 1e3) / 1e3d; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (baseUnitValue * 1e1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (baseUnitValue * 1e-1) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (baseUnitValue * 1e-3) / 1e6d; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (baseUnitValue * 1e3) / 1e6d; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (baseUnitValue * 1e7) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (baseUnitValue * 1e5) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMeter: return (baseUnitValue * 1e3) / 1e-3d; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (baseUnitValue * 1e9) / 1e-3d; - case MassMomentOfInertiaUnit.PoundSquareFoot: return baseUnitValue / 4.21401101e-2; - case MassMomentOfInertiaUnit.PoundSquareInch: return baseUnitValue / 2.9263965e-4; - case MassMomentOfInertiaUnit.SlugSquareFoot: return baseUnitValue / 1.3558179619; - case MassMomentOfInertiaUnit.SlugSquareInch: return baseUnitValue / 9.41540242e-3; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: return baseUnitValue * 1e1; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: return baseUnitValue * 1e-1; - case MassMomentOfInertiaUnit.TonneSquareMeter: return baseUnitValue * 1e-3; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: return baseUnitValue * 1e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.g.cs deleted file mode 100644 index c31ae0eae1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEnergy.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar energy is the amount of energy stored in 1 mole of a substance. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MolarEnergy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarEnergyUnit? _unit; - - static MolarEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); - BaseUnit = MolarEnergyUnit.JoulePerMole; - MaxValue = new MolarEnergy(double.MaxValue, BaseUnit); - MinValue = new MolarEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.MolarEnergy; - Units = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); - Zero = new MolarEnergy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MolarEnergy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerMole. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MolarEnergy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MolarEnergy(double value, MolarEnergyUnit unit) - { - if (unit == MolarEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. - /// - public static MolarEnergyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MolarEnergy - /// - public static MolarEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of MolarEnergy - /// - public static MolarEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MolarEnergy quantity. - /// - public static MolarEnergyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. - /// - public static MolarEnergy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MolarEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MolarEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromJoulesPerMole(double joulespermole) - { - double value = (double) joulespermole; - return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromKilojoulesPerMole(double kilojoulespermole) - { - double value = (double) kilojoulespermole; - return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEnergy FromMegajoulesPerMole(double megajoulespermole) - { - double value = (double) megajoulespermole; - return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarEnergy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) - { - return new MolarEnergy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarEnergy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MolarEnergy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MolarEnergyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MolarEnergyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarEnergy objMolarEnergy)) throw new ArgumentException("Expected type MolarEnergy.", nameof(obj)); - - return CompareTo(objMolarEnergy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MolarEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MolarEnergy objMolarEnergy)) - return false; - - return Equals(objMolarEnergy); - } - - public bool Equals(MolarEnergy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MolarEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MolarEnergyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEnergyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarEnergy to another MolarEnergy with the unit representation . - /// - /// A MolarEnergy with the specified unit. - public MolarEnergy ToUnit(MolarEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarEnergyUnit.JoulePerMole: return _value; - case MolarEnergyUnit.KilojoulePerMole: return (_value) * 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarEnergyUnit.JoulePerMole: return baseUnitValue; - case MolarEnergyUnit.KilojoulePerMole: return (baseUnitValue) / 1e3d; - case MolarEnergyUnit.MegajoulePerMole: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.g.cs deleted file mode 100644 index e94443e04b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarEntropy.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MolarEntropy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarEntropyUnit? _unit; - - static MolarEntropy() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); - BaseUnit = MolarEntropyUnit.JoulePerMoleKelvin; - MaxValue = new MolarEntropy(double.MaxValue, BaseUnit); - MinValue = new MolarEntropy(double.MinValue, BaseUnit); - QuantityType = QuantityType.MolarEntropy; - Units = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); - Zero = new MolarEntropy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MolarEntropy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerMoleKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MolarEntropy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MolarEntropy(double value, MolarEntropyUnit unit) - { - if (unit == MolarEntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. - /// - public static MolarEntropyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MolarEntropy - /// - public static MolarEntropy MaxValue { get; } - - /// - /// Represents the smallest possible value of MolarEntropy - /// - public static MolarEntropy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MolarEntropy quantity. - /// - public static MolarEntropyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. - /// - public static MolarEntropy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MolarEntropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); - - #endregion - - #region Static Methods - - 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)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MolarEntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromJoulesPerMoleKelvin(double joulespermolekelvin) - { - double value = (double) joulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromKilojoulesPerMoleKelvin(double kilojoulespermolekelvin) - { - double value = (double) kilojoulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarEntropy FromMegajoulesPerMoleKelvin(double megajoulespermolekelvin) - { - double value = (double) megajoulespermolekelvin; - return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarEntropy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) - { - return new MolarEntropy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarEntropy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarEntropy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarEntropy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MolarEntropy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarEntropyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MolarEntropyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MolarEntropyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarEntropy objMolarEntropy)) throw new ArgumentException("Expected type MolarEntropy.", nameof(obj)); - - return CompareTo(objMolarEntropy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MolarEntropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MolarEntropy objMolarEntropy)) - return false; - - return Equals(objMolarEntropy); - } - - public bool Equals(MolarEntropy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MolarEntropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEntropy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MolarEntropyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEntropyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarEntropy to another MolarEntropy with the unit representation . - /// - /// A MolarEntropy with the specified unit. - public MolarEntropy ToUnit(MolarEntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarEntropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return _value; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (_value) * 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarEntropyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: return baseUnitValue; - case MolarEntropyUnit.KilojoulePerMoleKelvin: return (baseUnitValue) / 1e3d; - case MolarEntropyUnit.MegajoulePerMoleKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.g.cs deleted file mode 100644 index 9d15caad7a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/MolarMass.g.cs +++ /dev/null @@ -1,814 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class MolarMass : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarMassUnit? _unit; - - static MolarMass() - { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); - BaseUnit = MolarMassUnit.KilogramPerMole; - MaxValue = new MolarMass(double.MaxValue, BaseUnit); - MinValue = new MolarMass(double.MinValue, BaseUnit); - QuantityType = QuantityType.MolarMass; - Units = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); - Zero = new MolarMass(0, BaseUnit); - Info = new QuantityInfo(QuantityType.MolarMass, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KilogramPerMole. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public MolarMass() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private MolarMass(double value, MolarMassUnit unit) - { - if (unit == MolarMassUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. - /// - public static MolarMassUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of MolarMass - /// - public static MolarMass MaxValue { get; } - - /// - /// Represents the smallest possible value of MolarMass - /// - public static MolarMass MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the MolarMass quantity. - /// - public static MolarMassUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. - /// - public static MolarMass Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => MolarMass.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => MolarMass.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerMole => As(MolarMassUnit.GramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); - - #endregion - - #region Static Methods - - 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[]{"фунт/моль"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MolarMassUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromCentigramsPerMole(double centigramspermole) - { - double value = (double) centigramspermole; - return new MolarMass(value, MolarMassUnit.CentigramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromDecagramsPerMole(double decagramspermole) - { - double value = (double) decagramspermole; - return new MolarMass(value, MolarMassUnit.DecagramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromDecigramsPerMole(double decigramspermole) - { - double value = (double) decigramspermole; - return new MolarMass(value, MolarMassUnit.DecigramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromGramsPerMole(double gramspermole) - { - double value = (double) gramspermole; - return new MolarMass(value, MolarMassUnit.GramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromHectogramsPerMole(double hectogramspermole) - { - double value = (double) hectogramspermole; - return new MolarMass(value, MolarMassUnit.HectogramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromKilogramsPerMole(double kilogramspermole) - { - double value = (double) kilogramspermole; - return new MolarMass(value, MolarMassUnit.KilogramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) - { - double value = (double) kilopoundspermole; - return new MolarMass(value, MolarMassUnit.KilopoundPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMegapoundsPerMole(double megapoundspermole) - { - double value = (double) megapoundspermole; - return new MolarMass(value, MolarMassUnit.MegapoundPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMicrogramsPerMole(double microgramspermole) - { - double value = (double) microgramspermole; - return new MolarMass(value, MolarMassUnit.MicrogramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromMilligramsPerMole(double milligramspermole) - { - double value = (double) milligramspermole; - return new MolarMass(value, MolarMassUnit.MilligramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromNanogramsPerMole(double nanogramspermole) - { - double value = (double) nanogramspermole; - return new MolarMass(value, MolarMassUnit.NanogramPerMole); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static MolarMass FromPoundsPerMole(double poundspermole) - { - double value = (double) poundspermole; - return new MolarMass(value, MolarMassUnit.PoundPerMole); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// MolarMass unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static MolarMass From(double value, MolarMassUnit fromUnit) - { - return new MolarMass((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static MolarMass Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarMass Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out MolarMass result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out MolarMass result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarMassUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MolarMassUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MolarMassUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarMass objMolarMass)) throw new ArgumentException("Expected type MolarMass.", nameof(obj)); - - return CompareTo(objMolarMass); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(MolarMass other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is MolarMass objMolarMass)) - return false; - - return Equals(objMolarMass); - } - - public bool Equals(MolarMass other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another MolarMass within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarMass. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MolarMassUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarMassUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this MolarMass to another MolarMass with the unit representation . - /// - /// A MolarMass with the specified unit. - public MolarMass ToUnit(MolarMassUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new MolarMass(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarMassUnit.CentigramPerMole: return (_value / 1e3) * 1e-2d; - case MolarMassUnit.DecagramPerMole: return (_value / 1e3) * 1e1d; - case MolarMassUnit.DecigramPerMole: return (_value / 1e3) * 1e-1d; - case MolarMassUnit.GramPerMole: return _value / 1e3; - case MolarMassUnit.HectogramPerMole: return (_value / 1e3) * 1e2d; - case MolarMassUnit.KilogramPerMole: return (_value / 1e3) * 1e3d; - case MolarMassUnit.KilopoundPerMole: return (_value * 0.45359237) * 1e3d; - case MolarMassUnit.MegapoundPerMole: return (_value * 0.45359237) * 1e6d; - case MolarMassUnit.MicrogramPerMole: return (_value / 1e3) * 1e-6d; - case MolarMassUnit.MilligramPerMole: return (_value / 1e3) * 1e-3d; - case MolarMassUnit.NanogramPerMole: return (_value / 1e3) * 1e-9d; - case MolarMassUnit.PoundPerMole: return _value * 0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarMassUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarMassUnit.CentigramPerMole: return (baseUnitValue * 1e3) / 1e-2d; - case MolarMassUnit.DecagramPerMole: return (baseUnitValue * 1e3) / 1e1d; - case MolarMassUnit.DecigramPerMole: return (baseUnitValue * 1e3) / 1e-1d; - case MolarMassUnit.GramPerMole: return baseUnitValue * 1e3; - case MolarMassUnit.HectogramPerMole: return (baseUnitValue * 1e3) / 1e2d; - case MolarMassUnit.KilogramPerMole: return (baseUnitValue * 1e3) / 1e3d; - case MolarMassUnit.KilopoundPerMole: return (baseUnitValue / 0.45359237) / 1e3d; - case MolarMassUnit.MegapoundPerMole: return (baseUnitValue / 0.45359237) / 1e6d; - case MolarMassUnit.MicrogramPerMole: return (baseUnitValue * 1e3) / 1e-6d; - case MolarMassUnit.MilligramPerMole: return (baseUnitValue * 1e3) / 1e-3d; - case MolarMassUnit.NanogramPerMole: return (baseUnitValue * 1e3) / 1e-9d; - case MolarMassUnit.PoundPerMole: return baseUnitValue / 0.45359237; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.g.cs deleted file mode 100644 index 5f8f10b521..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Molarity.g.cs +++ /dev/null @@ -1,772 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. - /// - /// - /// https://en.wikipedia.org/wiki/Molar_concentration - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Molarity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly MolarityUnit? _unit; - - static Molarity() - { - BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); - BaseUnit = MolarityUnit.MolesPerCubicMeter; - MaxValue = new Molarity(double.MaxValue, BaseUnit); - MinValue = new Molarity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Molarity; - Units = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); - Zero = new Molarity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Molarity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit MolesPerCubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Molarity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Molarity(double value, MolarityUnit unit) - { - if (unit == MolarityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Molarity, which is MolesPerCubicMeter. All conversions go via this value. - /// - public static MolarityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Molarity - /// - public static Molarity MaxValue { get; } - - /// - /// Represents the smallest possible value of Molarity - /// - public static Molarity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Molarity quantity. - /// - public static MolarityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MolesPerCubicMeter. - /// - public static Molarity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Molarity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Molarity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentimolesPerLiter => As(MolarityUnit.CentimolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimolesPerLiter => As(MolarityUnit.DecimolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double FemtomolesPerLiter => As(MolarityUnit.FemtomolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicromolesPerLiter => As(MolarityUnit.MicromolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimolesPerLiter => As(MolarityUnit.MillimolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MolesPerCubicMeter => As(MolarityUnit.MolePerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MolesPerLiter => As(MolarityUnit.MolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanomolesPerLiter => As(MolarityUnit.NanomolePerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicomolesPerLiter => As(MolarityUnit.PicomolePerLiter); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.CentimolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"cmol/L", "cM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.CentimolesPerLiter, new CultureInfo("en-US"), false, false, new string[]{"cmol/L", "cM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.DecimolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"dmol/L", "dM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.DecimolesPerLiter, new CultureInfo("en-US"), false, false, 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.MicromolesPerLiter, new CultureInfo("en-US"), false, false, new string[]{"µmol/L", "µM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MillimolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"mmol/L", "mM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MillimolesPerLiter, new CultureInfo("en-US"), false, false, 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.MolesPerCubicMeter, new CultureInfo("en-US"), false, false, new string[]{"mol/m³"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MolesPerLiter, new CultureInfo("en-US"), false, false, new string[]{"mol/L", "M"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.NanomolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"nmol/L", "nM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.NanomolesPerLiter, new CultureInfo("en-US"), false, false, new string[]{"nmol/L", "nM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.PicomolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"pmol/L", "pM"}); - unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.PicomolesPerLiter, new CultureInfo("en-US"), false, false, new string[]{"pmol/L", "pM"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(MolarityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromCentimolesPerLiter(double centimolesperliter) - { - double value = (double) centimolesperliter; - return new Molarity(value, MolarityUnit.CentimolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromDecimolesPerLiter(double decimolesperliter) - { - double value = (double) decimolesperliter; - return new Molarity(value, MolarityUnit.DecimolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromFemtomolesPerLiter(double femtomolesperliter) - { - double value = (double) femtomolesperliter; - return new Molarity(value, MolarityUnit.FemtomolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMicromolesPerLiter(double micromolesperliter) - { - double value = (double) micromolesperliter; - return new Molarity(value, MolarityUnit.MicromolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMillimolesPerLiter(double millimolesperliter) - { - double value = (double) millimolesperliter; - return new Molarity(value, MolarityUnit.MillimolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMolesPerCubicMeter(double molespercubicmeter) - { - double value = (double) molespercubicmeter; - return new Molarity(value, MolarityUnit.MolePerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromMolesPerLiter(double molesperliter) - { - double value = (double) molesperliter; - return new Molarity(value, MolarityUnit.MolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromNanomolesPerLiter(double nanomolesperliter) - { - double value = (double) nanomolesperliter; - return new Molarity(value, MolarityUnit.NanomolePerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Molarity FromPicomolesPerLiter(double picomolesperliter) - { - double value = (double) picomolesperliter; - return new Molarity(value, MolarityUnit.PicomolePerLiter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Molarity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Molarity From(double value, MolarityUnit fromUnit) - { - return new Molarity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Molarity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Molarity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Molarity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Molarity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static MolarityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out MolarityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out MolarityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Molarity objMolarity)) throw new ArgumentException("Expected type Molarity.", nameof(obj)); - - return CompareTo(objMolarity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Molarity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Molarity objMolarity)) - return false; - - return Equals(objMolarity); - } - - public bool Equals(Molarity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Molarity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Molarity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Molarity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((MolarityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Molarity to another Molarity with the unit representation . - /// - /// A Molarity with the specified unit. - public Molarity ToUnit(MolarityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Molarity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case MolarityUnit.CentimolePerLiter: return (_value / 1e-3) * 1e-2d; - case MolarityUnit.CentimolesPerLiter: return (_value / 1e-3) * 1e-2d; - case MolarityUnit.DecimolePerLiter: return (_value / 1e-3) * 1e-1d; - case MolarityUnit.DecimolesPerLiter: return (_value / 1e-3) * 1e-1d; - case MolarityUnit.FemtomolePerLiter: return (_value / 1e-3) * 1e-15d; - case MolarityUnit.MicromolePerLiter: return (_value / 1e-3) * 1e-6d; - case MolarityUnit.MicromolesPerLiter: return (_value / 1e-3) * 1e-6d; - case MolarityUnit.MillimolePerLiter: return (_value / 1e-3) * 1e-3d; - case MolarityUnit.MillimolesPerLiter: return (_value / 1e-3) * 1e-3d; - case MolarityUnit.MolePerCubicMeter: return _value; - case MolarityUnit.MolePerLiter: return _value / 1e-3; - case MolarityUnit.MolesPerCubicMeter: return _value; - case MolarityUnit.MolesPerLiter: return _value / 1e-3; - case MolarityUnit.NanomolePerLiter: return (_value / 1e-3) * 1e-9d; - case MolarityUnit.NanomolesPerLiter: return (_value / 1e-3) * 1e-9d; - case MolarityUnit.PicomolePerLiter: return (_value / 1e-3) * 1e-12d; - case MolarityUnit.PicomolesPerLiter: return (_value / 1e-3) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(MolarityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case MolarityUnit.CentimolePerLiter: return (baseUnitValue * 1e-3) / 1e-2d; - case MolarityUnit.CentimolesPerLiter: return (baseUnitValue * 1e-3) / 1e-2d; - case MolarityUnit.DecimolePerLiter: return (baseUnitValue * 1e-3) / 1e-1d; - case MolarityUnit.DecimolesPerLiter: return (baseUnitValue * 1e-3) / 1e-1d; - case MolarityUnit.FemtomolePerLiter: return (baseUnitValue * 1e-3) / 1e-15d; - case MolarityUnit.MicromolePerLiter: return (baseUnitValue * 1e-3) / 1e-6d; - case MolarityUnit.MicromolesPerLiter: return (baseUnitValue * 1e-3) / 1e-6d; - case MolarityUnit.MillimolePerLiter: return (baseUnitValue * 1e-3) / 1e-3d; - case MolarityUnit.MillimolesPerLiter: return (baseUnitValue * 1e-3) / 1e-3d; - case MolarityUnit.MolePerCubicMeter: return baseUnitValue; - case MolarityUnit.MolePerLiter: return baseUnitValue * 1e-3; - case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; - case MolarityUnit.MolesPerLiter: return baseUnitValue * 1e-3; - case MolarityUnit.NanomolePerLiter: return (baseUnitValue * 1e-3) / 1e-9d; - case MolarityUnit.NanomolesPerLiter: return (baseUnitValue * 1e-3) / 1e-9d; - case MolarityUnit.PicomolePerLiter: return (baseUnitValue * 1e-3) / 1e-12d; - case MolarityUnit.PicomolesPerLiter: return (baseUnitValue * 1e-3) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.g.cs deleted file mode 100644 index 534a6d21c2..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permeability.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself. - /// - /// - /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Permeability : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PermeabilityUnit? _unit; - - static Permeability() - { - BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); - BaseUnit = PermeabilityUnit.HenryPerMeter; - MaxValue = new Permeability(double.MaxValue, BaseUnit); - MinValue = new Permeability(double.MinValue, BaseUnit); - QuantityType = QuantityType.Permeability; - Units = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); - Zero = new Permeability(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Permeability, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit HenryPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Permeability() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Permeability(double value, PermeabilityUnit unit) - { - if (unit == PermeabilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. - /// - public static PermeabilityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Permeability - /// - public static Permeability MaxValue { get; } - - /// - /// Represents the smallest possible value of Permeability - /// - public static Permeability MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Permeability quantity. - /// - public static PermeabilityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. - /// - public static Permeability Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Permeability.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Permeability.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(PermeabilityUnit.HenryPerMeter, new CultureInfo("en-US"), false, true, new string[]{"H/m"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PermeabilityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Permeability FromHenriesPerMeter(double henriespermeter) - { - double value = (double) henriespermeter; - return new Permeability(value, PermeabilityUnit.HenryPerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Permeability unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Permeability From(double value, PermeabilityUnit fromUnit) - { - return new Permeability((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Permeability Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Permeability Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Permeability result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Permeability result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermeabilityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PermeabilityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PermeabilityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Permeability objPermeability)) throw new ArgumentException("Expected type Permeability.", nameof(obj)); - - return CompareTo(objPermeability); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Permeability other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Permeability objPermeability)) - return false; - - return Equals(objPermeability); - } - - public bool Equals(Permeability other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Permeability within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Permeability other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permeability. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PermeabilityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermeabilityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Permeability to another Permeability with the unit representation . - /// - /// A Permeability with the specified unit. - public Permeability ToUnit(PermeabilityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Permeability(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PermeabilityUnit.HenryPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PermeabilityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PermeabilityUnit.HenryPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.g.cs deleted file mode 100644 index 78a9b9efb8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Permittivity.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium. - /// - /// - /// https://en.wikipedia.org/wiki/Permittivity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Permittivity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PermittivityUnit? _unit; - - static Permittivity() - { - BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); - BaseUnit = PermittivityUnit.FaradPerMeter; - MaxValue = new Permittivity(double.MaxValue, BaseUnit); - MinValue = new Permittivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Permittivity; - Units = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); - Zero = new Permittivity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Permittivity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit FaradPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Permittivity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Permittivity(double value, PermittivityUnit unit) - { - if (unit == PermittivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. - /// - public static PermittivityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Permittivity - /// - public static Permittivity MaxValue { get; } - - /// - /// Represents the smallest possible value of Permittivity - /// - public static Permittivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Permittivity quantity. - /// - public static PermittivityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. - /// - public static Permittivity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Permittivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Permittivity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(PermittivityUnit.FaradPerMeter, new CultureInfo("en-US"), false, true, new string[]{"F/m"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PermittivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Permittivity FromFaradsPerMeter(double faradspermeter) - { - double value = (double) faradspermeter; - return new Permittivity(value, PermittivityUnit.FaradPerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Permittivity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Permittivity From(double value, PermittivityUnit fromUnit) - { - return new Permittivity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Permittivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Permittivity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Permittivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Permittivity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PermittivityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PermittivityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PermittivityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Permittivity objPermittivity)) throw new ArgumentException("Expected type Permittivity.", nameof(obj)); - - return CompareTo(objPermittivity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Permittivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Permittivity objPermittivity)) - return false; - - return Equals(objPermittivity); - } - - public bool Equals(Permittivity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Permittivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Permittivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permittivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PermittivityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermittivityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Permittivity to another Permittivity with the unit representation . - /// - /// A Permittivity with the specified unit. - public Permittivity ToUnit(PermittivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Permittivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PermittivityUnit.FaradPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PermittivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PermittivityUnit.FaradPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PorousMediumPermeability.g.cs deleted file mode 100644 index bf6a1000d8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ /dev/null @@ -1,672 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In fluid mechanics, permeability is the measure of the ability of a porous material to allow fluids to pass through it. - /// - /// - /// https://en.wikipedia.org/wiki/Permeability_(Earth_sciences) - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PorousMediumPermeability : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PorousMediumPermeabilityUnit? _unit; - - static PorousMediumPermeability() - { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - BaseUnit = PorousMediumPermeabilityUnit.SquareMeter; - MaxValue = new PorousMediumPermeability(double.MaxValue, BaseUnit); - MinValue = new PorousMediumPermeability(double.MinValue, BaseUnit); - QuantityType = QuantityType.PorousMediumPermeability; - Units = Enum.GetValues(typeof(PorousMediumPermeabilityUnit)).Cast().Except(new PorousMediumPermeabilityUnit[]{ PorousMediumPermeabilityUnit.Undefined }).ToArray(); - Zero = new PorousMediumPermeability(0, BaseUnit); - Info = new QuantityInfo(QuantityType.PorousMediumPermeability, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit SquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public PorousMediumPermeability() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private PorousMediumPermeability(double value, PorousMediumPermeabilityUnit unit) - { - if (unit == PorousMediumPermeabilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of PorousMediumPermeability, which is SquareMeter. All conversions go via this value. - /// - public static PorousMediumPermeabilityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of PorousMediumPermeability - /// - public static PorousMediumPermeability MaxValue { get; } - - /// - /// Represents the smallest possible value of PorousMediumPermeability - /// - public static PorousMediumPermeability MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the PorousMediumPermeability quantity. - /// - public static PorousMediumPermeabilityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. - /// - public static PorousMediumPermeability Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PorousMediumPermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => PorousMediumPermeability.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PorousMediumPermeability.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Darcys => As(PorousMediumPermeabilityUnit.Darcy); - - /// - /// Gets a value of this quantity converted into - /// - public double Microdarcys => As(PorousMediumPermeabilityUnit.Microdarcy); - - /// - /// Gets a value of this quantity converted into - /// - public double Millidarcys => As(PorousMediumPermeabilityUnit.Millidarcy); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareCentimeters => As(PorousMediumPermeabilityUnit.SquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMeters => As(PorousMediumPermeabilityUnit.SquareMeter); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PorousMediumPermeabilityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PorousMediumPermeabilityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PorousMediumPermeability FromDarcys(double darcys) - { - double value = (double) darcys; - return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Darcy); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PorousMediumPermeability FromMicrodarcys(double microdarcys) - { - double value = (double) microdarcys; - return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Microdarcy); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PorousMediumPermeability FromMillidarcys(double millidarcys) - { - double value = (double) millidarcys; - return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Millidarcy); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PorousMediumPermeability FromSquareCentimeters(double squarecentimeters) - { - double value = (double) squarecentimeters; - return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PorousMediumPermeability FromSquareMeters(double squaremeters) - { - double value = (double) squaremeters; - return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PorousMediumPermeability unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PorousMediumPermeability From(double value, PorousMediumPermeabilityUnit fromUnit) - { - return new PorousMediumPermeability((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PorousMediumPermeability Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PorousMediumPermeability Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PorousMediumPermeability result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out PorousMediumPermeability result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PorousMediumPermeabilityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PorousMediumPermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PorousMediumPermeabilityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PorousMediumPermeabilityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PorousMediumPermeability objPorousMediumPermeability)) throw new ArgumentException("Expected type PorousMediumPermeability.", nameof(obj)); - - return CompareTo(objPorousMediumPermeability); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(PorousMediumPermeability other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is PorousMediumPermeability objPorousMediumPermeability)) - return false; - - return Equals(objPorousMediumPermeability); - } - - public bool Equals(PorousMediumPermeability other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PorousMediumPermeability within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PorousMediumPermeability. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PorousMediumPermeabilityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PorousMediumPermeabilityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PorousMediumPermeability to another PorousMediumPermeability with the unit representation . - /// - /// A PorousMediumPermeability with the specified unit. - public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PorousMediumPermeability(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PorousMediumPermeabilityUnit.Darcy: return _value * 9.869233e-13; - case PorousMediumPermeabilityUnit.Microdarcy: return (_value * 9.869233e-13) * 1e-6d; - case PorousMediumPermeabilityUnit.Millidarcy: return (_value * 9.869233e-13) * 1e-3d; - case PorousMediumPermeabilityUnit.SquareCentimeter: return _value * 1e-4; - case PorousMediumPermeabilityUnit.SquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PorousMediumPermeabilityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PorousMediumPermeabilityUnit.Darcy: return baseUnitValue / 9.869233e-13; - case PorousMediumPermeabilityUnit.Microdarcy: return (baseUnitValue / 9.869233e-13) / 1e-6d; - case PorousMediumPermeabilityUnit.Millidarcy: return (baseUnitValue / 9.869233e-13) / 1e-3d; - case PorousMediumPermeabilityUnit.SquareCentimeter: return baseUnitValue / 1e-4; - case PorousMediumPermeabilityUnit.SquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.g.cs deleted file mode 100644 index 16fe168464..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Power.g.cs +++ /dev/null @@ -1,1068 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Power : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly decimal _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerUnit? _unit; - - static Power() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = PowerUnit.Watt; - MaxValue = new Power(decimal.MaxValue, BaseUnit); - MinValue = new Power(decimal.MinValue, BaseUnit); - QuantityType = QuantityType.Power; - Units = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); - Zero = new Power(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Power, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Watt. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Power() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Power(decimal value, PowerUnit unit) - { - if (unit == PowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = value; - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Power, which is Watt. All conversions go via this value. - /// - public static PowerUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Power - /// - public static Power MaxValue { get; } - - /// - /// Represents the smallest possible value of Power - /// - public static Power MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Power quantity. - /// - public static PowerUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Watt. - /// - public static Power Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Power.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Power.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); - - /// - /// Gets a value of this quantity converted into - /// - public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Decawatts => As(PowerUnit.Decawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Deciwatts => As(PowerUnit.Deciwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); - - /// - /// Gets a value of this quantity converted into - /// - public double Femtowatts => As(PowerUnit.Femtowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigawatts => As(PowerUnit.Gigawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerHour => As(PowerUnit.JoulePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilowatts => As(PowerUnit.Kilowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); - - /// - /// Gets a value of this quantity converted into - /// - public double MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Megawatts => As(PowerUnit.Megawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double MetricHorsepower => As(PowerUnit.MetricHorsepower); - - /// - /// Gets a value of this quantity converted into - /// - public double Microwatts => As(PowerUnit.Microwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliwatts => As(PowerUnit.Milliwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Nanowatts => As(PowerUnit.Nanowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Petawatts => As(PowerUnit.Petawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Picowatts => As(PowerUnit.Picowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Terawatts => As(PowerUnit.Terawatt); - - /// - /// Gets a value of this quantity converted into - /// - public double Watts => As(PowerUnit.Watt); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PowerUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromBoilerHorsepower(double boilerhorsepower) - { - decimal value = (decimal) boilerhorsepower; - return new Power(value, PowerUnit.BoilerHorsepower); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromBritishThermalUnitsPerHour(double britishthermalunitsperhour) - { - decimal value = (decimal) britishthermalunitsperhour; - return new Power(value, PowerUnit.BritishThermalUnitPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromDecawatts(double decawatts) - { - decimal value = (decimal) decawatts; - return new Power(value, PowerUnit.Decawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromDeciwatts(double deciwatts) - { - decimal value = (decimal) deciwatts; - return new Power(value, PowerUnit.Deciwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromElectricalHorsepower(double electricalhorsepower) - { - decimal value = (decimal) electricalhorsepower; - return new Power(value, PowerUnit.ElectricalHorsepower); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromFemtowatts(double femtowatts) - { - decimal value = (decimal) femtowatts; - return new Power(value, PowerUnit.Femtowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromGigajoulesPerHour(double gigajoulesperhour) - { - decimal value = (decimal) gigajoulesperhour; - return new Power(value, PowerUnit.GigajoulePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromGigawatts(double gigawatts) - { - decimal value = (decimal) gigawatts; - return new Power(value, PowerUnit.Gigawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromHydraulicHorsepower(double hydraulichorsepower) - { - decimal value = (decimal) hydraulichorsepower; - return new Power(value, PowerUnit.HydraulicHorsepower); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromJoulesPerHour(double joulesperhour) - { - decimal value = (decimal) joulesperhour; - return new Power(value, PowerUnit.JoulePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilobritishThermalUnitsPerHour(double kilobritishthermalunitsperhour) - { - decimal value = (decimal) kilobritishthermalunitsperhour; - return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilojoulesPerHour(double kilojoulesperhour) - { - decimal value = (decimal) kilojoulesperhour; - return new Power(value, PowerUnit.KilojoulePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromKilowatts(double kilowatts) - { - decimal value = (decimal) kilowatts; - return new Power(value, PowerUnit.Kilowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMechanicalHorsepower(double mechanicalhorsepower) - { - decimal value = (decimal) mechanicalhorsepower; - return new Power(value, PowerUnit.MechanicalHorsepower); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMegabritishThermalUnitsPerHour(double megabritishthermalunitsperhour) - { - decimal value = (decimal) megabritishthermalunitsperhour; - return new Power(value, PowerUnit.MegabritishThermalUnitPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMegajoulesPerHour(double megajoulesperhour) - { - decimal value = (decimal) megajoulesperhour; - return new Power(value, PowerUnit.MegajoulePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMegawatts(double megawatts) - { - decimal value = (decimal) megawatts; - return new Power(value, PowerUnit.Megawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMetricHorsepower(double metrichorsepower) - { - decimal value = (decimal) metrichorsepower; - return new Power(value, PowerUnit.MetricHorsepower); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMicrowatts(double microwatts) - { - decimal value = (decimal) microwatts; - return new Power(value, PowerUnit.Microwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMillijoulesPerHour(double millijoulesperhour) - { - decimal value = (decimal) millijoulesperhour; - return new Power(value, PowerUnit.MillijoulePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromMilliwatts(double milliwatts) - { - decimal value = (decimal) milliwatts; - return new Power(value, PowerUnit.Milliwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromNanowatts(double nanowatts) - { - decimal value = (decimal) nanowatts; - return new Power(value, PowerUnit.Nanowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromPetawatts(double petawatts) - { - decimal value = (decimal) petawatts; - return new Power(value, PowerUnit.Petawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromPicowatts(double picowatts) - { - decimal value = (decimal) picowatts; - return new Power(value, PowerUnit.Picowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromTerawatts(double terawatts) - { - decimal value = (decimal) terawatts; - return new Power(value, PowerUnit.Terawatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Power FromWatts(double watts) - { - decimal value = (decimal) watts; - return new Power(value, PowerUnit.Watt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Power unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Power From(double value, PowerUnit fromUnit) - { - return new Power((decimal)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Power Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Power Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Power result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Power result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PowerUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PowerUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Power objPower)) throw new ArgumentException("Expected type Power.", nameof(obj)); - - return CompareTo(objPower); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Power other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Power objPower)) - return false; - - return Equals(objPower); - } - - public bool Equals(Power other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Power within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Power other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Power. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PowerUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Power to another Power with the unit representation . - /// - /// A Power with the specified unit. - public Power ToUnit(PowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Power(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private decimal AsBaseUnit() - { - switch(Unit) - { - case PowerUnit.BoilerHorsepower: return _value * 9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return _value * 0.293071m; - case PowerUnit.Decawatt: return (_value) * 1e1m; - case PowerUnit.Deciwatt: return (_value) * 1e-1m; - case PowerUnit.ElectricalHorsepower: return _value * 746m; - case PowerUnit.Femtowatt: return (_value) * 1e-15m; - case PowerUnit.GigajoulePerHour: return (_value / 3600m) * 1e9m; - case PowerUnit.Gigawatt: return (_value) * 1e9m; - case PowerUnit.HydraulicHorsepower: return _value * 745.69988145m; - case PowerUnit.JoulePerHour: return _value / 3600m; - case PowerUnit.KilobritishThermalUnitPerHour: return (_value * 0.293071m) * 1e3m; - case PowerUnit.KilojoulePerHour: return (_value / 3600m) * 1e3m; - case PowerUnit.Kilowatt: return (_value) * 1e3m; - case PowerUnit.MechanicalHorsepower: return _value * 745.69m; - case PowerUnit.MegabritishThermalUnitPerHour: return (_value * 0.293071m) * 1e6m; - case PowerUnit.MegajoulePerHour: return (_value / 3600m) * 1e6m; - case PowerUnit.Megawatt: return (_value) * 1e6m; - case PowerUnit.MetricHorsepower: return _value * 735.49875m; - case PowerUnit.Microwatt: return (_value) * 1e-6m; - case PowerUnit.MillijoulePerHour: return (_value / 3600m) * 1e-3m; - case PowerUnit.Milliwatt: return (_value) * 1e-3m; - case PowerUnit.Nanowatt: return (_value) * 1e-9m; - case PowerUnit.Petawatt: return (_value) * 1e15m; - case PowerUnit.Picowatt: return (_value) * 1e-12m; - case PowerUnit.Terawatt: return (_value) * 1e12m; - case PowerUnit.Watt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private decimal AsBaseNumericType(PowerUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerUnit.BoilerHorsepower: return baseUnitValue / 9812.5m; - case PowerUnit.BritishThermalUnitPerHour: return baseUnitValue / 0.293071m; - case PowerUnit.Decawatt: return (baseUnitValue) / 1e1m; - case PowerUnit.Deciwatt: return (baseUnitValue) / 1e-1m; - case PowerUnit.ElectricalHorsepower: return baseUnitValue / 746m; - case PowerUnit.Femtowatt: return (baseUnitValue) / 1e-15m; - case PowerUnit.GigajoulePerHour: return (baseUnitValue * 3600m) / 1e9m; - case PowerUnit.Gigawatt: return (baseUnitValue) / 1e9m; - case PowerUnit.HydraulicHorsepower: return baseUnitValue / 745.69988145m; - case PowerUnit.JoulePerHour: return baseUnitValue * 3600m; - case PowerUnit.KilobritishThermalUnitPerHour: return (baseUnitValue / 0.293071m) / 1e3m; - case PowerUnit.KilojoulePerHour: return (baseUnitValue * 3600m) / 1e3m; - case PowerUnit.Kilowatt: return (baseUnitValue) / 1e3m; - case PowerUnit.MechanicalHorsepower: return baseUnitValue / 745.69m; - case PowerUnit.MegabritishThermalUnitPerHour: return (baseUnitValue / 0.293071m) / 1e6m; - case PowerUnit.MegajoulePerHour: return (baseUnitValue * 3600m) / 1e6m; - case PowerUnit.Megawatt: return (baseUnitValue) / 1e6m; - case PowerUnit.MetricHorsepower: return baseUnitValue / 735.49875m; - case PowerUnit.Microwatt: return (baseUnitValue) / 1e-6m; - case PowerUnit.MillijoulePerHour: return (baseUnitValue * 3600m) / 1e-3m; - case PowerUnit.Milliwatt: return (baseUnitValue) / 1e-3m; - case PowerUnit.Nanowatt: return (baseUnitValue) / 1e-9m; - case PowerUnit.Petawatt: return (baseUnitValue) / 1e15m; - case PowerUnit.Picowatt: return (baseUnitValue) / 1e-12m; - case PowerUnit.Terawatt: return (baseUnitValue) / 1e12m; - case PowerUnit.Watt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.g.cs deleted file mode 100644 index 8b4f0e05bc..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerDensity.g.cs +++ /dev/null @@ -1,1410 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The amount of power in a volume. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PowerDensity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerDensityUnit? _unit; - - static PowerDensity() - { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - BaseUnit = PowerDensityUnit.WattPerCubicMeter; - MaxValue = new PowerDensity(double.MaxValue, BaseUnit); - MinValue = new PowerDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.PowerDensity; - Units = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); - Zero = new PowerDensity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.PowerDensity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit WattPerCubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public PowerDensity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private PowerDensity(double value, PowerDensityUnit unit) - { - if (unit == PowerDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. - /// - public static PowerDensityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of PowerDensity - /// - public static PowerDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of PowerDensity - /// - public static PowerDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the PowerDensity quantity. - /// - public static PowerDensityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. - /// - public static PowerDensity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => PowerDensity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PowerDensity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PowerDensityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PowerDensityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicFoot(double decawattspercubicfoot) - { - double value = (double) decawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicInch(double decawattspercubicinch) - { - double value = (double) decawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerCubicMeter(double decawattspercubicmeter) - { - double value = (double) decawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDecawattsPerLiter(double decawattsperliter) - { - double value = (double) decawattsperliter; - return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicFoot(double deciwattspercubicfoot) - { - double value = (double) deciwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicInch(double deciwattspercubicinch) - { - double value = (double) deciwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerCubicMeter(double deciwattspercubicmeter) - { - double value = (double) deciwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromDeciwattsPerLiter(double deciwattsperliter) - { - double value = (double) deciwattsperliter; - return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicFoot(double gigawattspercubicfoot) - { - double value = (double) gigawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicInch(double gigawattspercubicinch) - { - double value = (double) gigawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerCubicMeter(double gigawattspercubicmeter) - { - double value = (double) gigawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromGigawattsPerLiter(double gigawattsperliter) - { - double value = (double) gigawattsperliter; - return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicFoot(double kilowattspercubicfoot) - { - double value = (double) kilowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicInch(double kilowattspercubicinch) - { - double value = (double) kilowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerCubicMeter(double kilowattspercubicmeter) - { - double value = (double) kilowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromKilowattsPerLiter(double kilowattsperliter) - { - double value = (double) kilowattsperliter; - return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicFoot(double megawattspercubicfoot) - { - double value = (double) megawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicInch(double megawattspercubicinch) - { - double value = (double) megawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerCubicMeter(double megawattspercubicmeter) - { - double value = (double) megawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMegawattsPerLiter(double megawattsperliter) - { - double value = (double) megawattsperliter; - return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicFoot(double microwattspercubicfoot) - { - double value = (double) microwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicInch(double microwattspercubicinch) - { - double value = (double) microwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerCubicMeter(double microwattspercubicmeter) - { - double value = (double) microwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMicrowattsPerLiter(double microwattsperliter) - { - double value = (double) microwattsperliter; - return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicFoot(double milliwattspercubicfoot) - { - double value = (double) milliwattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicInch(double milliwattspercubicinch) - { - double value = (double) milliwattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerCubicMeter(double milliwattspercubicmeter) - { - double value = (double) milliwattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromMilliwattsPerLiter(double milliwattsperliter) - { - double value = (double) milliwattsperliter; - return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicFoot(double nanowattspercubicfoot) - { - double value = (double) nanowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicInch(double nanowattspercubicinch) - { - double value = (double) nanowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerCubicMeter(double nanowattspercubicmeter) - { - double value = (double) nanowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromNanowattsPerLiter(double nanowattsperliter) - { - double value = (double) nanowattsperliter; - return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicFoot(double picowattspercubicfoot) - { - double value = (double) picowattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicInch(double picowattspercubicinch) - { - double value = (double) picowattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerCubicMeter(double picowattspercubicmeter) - { - double value = (double) picowattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromPicowattsPerLiter(double picowattsperliter) - { - double value = (double) picowattsperliter; - return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicFoot(double terawattspercubicfoot) - { - double value = (double) terawattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicInch(double terawattspercubicinch) - { - double value = (double) terawattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerCubicMeter(double terawattspercubicmeter) - { - double value = (double) terawattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromTerawattsPerLiter(double terawattsperliter) - { - double value = (double) terawattsperliter; - return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicFoot(double wattspercubicfoot) - { - double value = (double) wattspercubicfoot; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicInch(double wattspercubicinch) - { - double value = (double) wattspercubicinch; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerCubicMeter(double wattspercubicmeter) - { - double value = (double) wattspercubicmeter; - return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerDensity FromWattsPerLiter(double wattsperliter) - { - double value = (double) wattsperliter; - return new PowerDensity(value, PowerDensityUnit.WattPerLiter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PowerDensity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PowerDensity From(double value, PowerDensityUnit fromUnit) - { - return new PowerDensity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PowerDensity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PowerDensity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PowerDensity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out PowerDensity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerDensityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PowerDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PowerDensityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PowerDensityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PowerDensity objPowerDensity)) throw new ArgumentException("Expected type PowerDensity.", nameof(obj)); - - return CompareTo(objPowerDensity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(PowerDensity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is PowerDensity objPowerDensity)) - return false; - - return Equals(objPowerDensity); - } - - public bool Equals(PowerDensity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PowerDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PowerDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PowerDensityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerDensityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PowerDensity to another PowerDensity with the unit representation . - /// - /// A PowerDensity with the specified unit. - public PowerDensity ToUnit(PowerDensityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PowerDensity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (_value * 6.102374409473228e4) * 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (_value) * 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (_value * 1.0e3) * 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (_value * 6.102374409473228e4) * 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (_value) * 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (_value * 1.0e3) * 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (_value * 6.102374409473228e4) * 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (_value) * 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (_value * 1.0e3) * 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (_value * 6.102374409473228e4) * 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (_value) * 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (_value * 1.0e3) * 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (_value * 6.102374409473228e4) * 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (_value) * 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (_value * 1.0e3) * 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (_value * 6.102374409473228e4) * 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (_value) * 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (_value * 1.0e3) * 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (_value * 6.102374409473228e4) * 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (_value) * 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (_value * 1.0e3) * 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (_value * 6.102374409473228e4) * 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (_value) * 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (_value * 1.0e3) * 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (_value * 6.102374409473228e4) * 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (_value) * 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (_value * 1.0e3) * 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (_value * 3.531466672148859e1) * 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (_value * 6.102374409473228e4) * 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (_value) * 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (_value * 1.0e3) * 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return _value * 3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return _value * 6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return _value; - case PowerDensityUnit.WattPerLiter: return _value * 1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PowerDensityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerDensityUnit.DecawattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e1d; - case PowerDensityUnit.DecawattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e1d; - case PowerDensityUnit.DecawattPerCubicMeter: return (baseUnitValue) / 1e1d; - case PowerDensityUnit.DecawattPerLiter: return (baseUnitValue / 1.0e3) / 1e1d; - case PowerDensityUnit.DeciwattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e-1d; - case PowerDensityUnit.DeciwattPerCubicMeter: return (baseUnitValue) / 1e-1d; - case PowerDensityUnit.DeciwattPerLiter: return (baseUnitValue / 1.0e3) / 1e-1d; - case PowerDensityUnit.GigawattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e9d; - case PowerDensityUnit.GigawattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e9d; - case PowerDensityUnit.GigawattPerCubicMeter: return (baseUnitValue) / 1e9d; - case PowerDensityUnit.GigawattPerLiter: return (baseUnitValue / 1.0e3) / 1e9d; - case PowerDensityUnit.KilowattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e3d; - case PowerDensityUnit.KilowattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e3d; - case PowerDensityUnit.KilowattPerCubicMeter: return (baseUnitValue) / 1e3d; - case PowerDensityUnit.KilowattPerLiter: return (baseUnitValue / 1.0e3) / 1e3d; - case PowerDensityUnit.MegawattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e6d; - case PowerDensityUnit.MegawattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e6d; - case PowerDensityUnit.MegawattPerCubicMeter: return (baseUnitValue) / 1e6d; - case PowerDensityUnit.MegawattPerLiter: return (baseUnitValue / 1.0e3) / 1e6d; - case PowerDensityUnit.MicrowattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e-6d; - case PowerDensityUnit.MicrowattPerCubicMeter: return (baseUnitValue) / 1e-6d; - case PowerDensityUnit.MicrowattPerLiter: return (baseUnitValue / 1.0e3) / 1e-6d; - case PowerDensityUnit.MilliwattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e-3d; - case PowerDensityUnit.MilliwattPerCubicMeter: return (baseUnitValue) / 1e-3d; - case PowerDensityUnit.MilliwattPerLiter: return (baseUnitValue / 1.0e3) / 1e-3d; - case PowerDensityUnit.NanowattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e-9d; - case PowerDensityUnit.NanowattPerCubicMeter: return (baseUnitValue) / 1e-9d; - case PowerDensityUnit.NanowattPerLiter: return (baseUnitValue / 1.0e3) / 1e-9d; - case PowerDensityUnit.PicowattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e-12d; - case PowerDensityUnit.PicowattPerCubicMeter: return (baseUnitValue) / 1e-12d; - case PowerDensityUnit.PicowattPerLiter: return (baseUnitValue / 1.0e3) / 1e-12d; - case PowerDensityUnit.TerawattPerCubicFoot: return (baseUnitValue / 3.531466672148859e1) / 1e12d; - case PowerDensityUnit.TerawattPerCubicInch: return (baseUnitValue / 6.102374409473228e4) / 1e12d; - case PowerDensityUnit.TerawattPerCubicMeter: return (baseUnitValue) / 1e12d; - case PowerDensityUnit.TerawattPerLiter: return (baseUnitValue / 1.0e3) / 1e12d; - case PowerDensityUnit.WattPerCubicFoot: return baseUnitValue / 3.531466672148859e1; - case PowerDensityUnit.WattPerCubicInch: return baseUnitValue / 6.102374409473228e4; - case PowerDensityUnit.WattPerCubicMeter: return baseUnitValue; - case PowerDensityUnit.WattPerLiter: return baseUnitValue / 1.0e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.g.cs deleted file mode 100644 index 73e941d3ac..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PowerRatio.g.cs +++ /dev/null @@ -1,612 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The strength of a signal expressed in decibels (dB) relative to one watt. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PowerRatio : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PowerRatioUnit? _unit; - - static PowerRatio() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = PowerRatioUnit.DecibelWatt; - MaxValue = new PowerRatio(double.MaxValue, BaseUnit); - MinValue = new PowerRatio(double.MinValue, BaseUnit); - QuantityType = QuantityType.PowerRatio; - Units = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); - Zero = new PowerRatio(0, BaseUnit); - Info = new QuantityInfo(QuantityType.PowerRatio, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DecibelWatt. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public PowerRatio() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private PowerRatio(double value, PowerRatioUnit unit) - { - if (unit == PowerRatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. - /// - public static PowerRatioUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of PowerRatio - /// - public static PowerRatio MaxValue { get; } - - /// - /// Represents the smallest possible value of PowerRatio - /// - public static PowerRatio MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the PowerRatio quantity. - /// - public static PowerRatioUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. - /// - public static PowerRatio Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => PowerRatio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PowerRatio.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); - - /// - /// Gets a value of this quantity converted into - /// - public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PowerRatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerRatio FromDecibelMilliwatts(double decibelmilliwatts) - { - double value = (double) decibelmilliwatts; - return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PowerRatio FromDecibelWatts(double decibelwatts) - { - double value = (double) decibelwatts; - return new PowerRatio(value, PowerRatioUnit.DecibelWatt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PowerRatio unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PowerRatio From(double value, PowerRatioUnit fromUnit) - { - return new PowerRatio((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PowerRatio Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PowerRatio Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PowerRatio result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out PowerRatio result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PowerRatioUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PowerRatioUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PowerRatioUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PowerRatio objPowerRatio)) throw new ArgumentException("Expected type PowerRatio.", nameof(obj)); - - return CompareTo(objPowerRatio); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(PowerRatio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is PowerRatio objPowerRatio)) - return false; - - return Equals(objPowerRatio); - } - - public bool Equals(PowerRatio other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PowerRatio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PowerRatio other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerRatio. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PowerRatioUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerRatioUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PowerRatio to another PowerRatio with the unit representation . - /// - /// A PowerRatio with the specified unit. - public PowerRatio ToUnit(PowerRatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PowerRatio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PowerRatioUnit.DecibelMilliwatt: return _value - 30; - case PowerRatioUnit.DecibelWatt: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PowerRatioUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PowerRatioUnit.DecibelMilliwatt: return baseUnitValue + 30; - case PowerRatioUnit.DecibelWatt: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.g.cs deleted file mode 100644 index 68defb78d1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Pressure.g.cs +++ /dev/null @@ -1,1498 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Pressure : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PressureUnit? _unit; - - static Pressure() - { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); - BaseUnit = PressureUnit.Pascal; - MaxValue = new Pressure(double.MaxValue, BaseUnit); - MinValue = new Pressure(double.MinValue, BaseUnit); - QuantityType = QuantityType.Pressure; - Units = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); - Zero = new Pressure(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Pressure, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Pascal. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Pressure() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Pressure(double value, PressureUnit unit) - { - if (unit == PressureUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Pressure, which is Pascal. All conversions go via this value. - /// - public static PressureUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Pressure - /// - public static Pressure MaxValue { get; } - - /// - /// Represents the smallest possible value of Pressure - /// - public static Pressure MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Pressure quantity. - /// - public static PressureUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. - /// - public static Pressure Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Pressure.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Pressure.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Atmospheres => As(PressureUnit.Atmosphere); - - /// - /// Gets a value of this quantity converted into - /// - public double Bars => As(PressureUnit.Bar); - - /// - /// Gets a value of this quantity converted into - /// - public double Centibars => As(PressureUnit.Centibar); - - /// - /// Gets a value of this quantity converted into - /// - public double Decapascals => As(PressureUnit.Decapascal); - - /// - /// Gets a value of this quantity converted into - /// - public double Decibars => As(PressureUnit.Decibar); - - /// - /// Gets a value of this quantity converted into - /// - public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetOfElevation => As(PressureUnit.FootOfElevation); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetOfHead => As(PressureUnit.FootOfHead); - - /// - /// Gets a value of this quantity converted into - /// - public double Gigapascals => As(PressureUnit.Gigapascal); - - /// - /// Gets a value of this quantity converted into - /// - public double Hectopascals => As(PressureUnit.Hectopascal); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesOfMercury => As(PressureUnit.InchOfMercury); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesOfWaterColumn => As(PressureUnit.InchOfWaterColumn); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilobars => As(PressureUnit.Kilobar); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Kilopascals => As(PressureUnit.Kilopascal); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerSquareMil => As(PressureUnit.KilopoundForcePerSquareMil); - - /// - /// Gets a value of this quantity converted into - /// - public double Megabars => As(PressureUnit.Megabar); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Megapascals => As(PressureUnit.Megapascal); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersOfElevation => As(PressureUnit.MeterOfElevation); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersOfHead => As(PressureUnit.MeterOfHead); - - /// - /// Gets a value of this quantity converted into - /// - public double Microbars => As(PressureUnit.Microbar); - - /// - /// Gets a value of this quantity converted into - /// - public double Micropascals => As(PressureUnit.Micropascal); - - /// - /// Gets a value of this quantity converted into - /// - public double Millibars => As(PressureUnit.Millibar); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimeterOfWaterColumn => As(PressureUnit.MillimeterOfWaterColumn); - - /// - /// Gets a value of this quantity converted into - /// - public double Millipascals => As(PressureUnit.Millipascal); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Pascals => As(PressureUnit.Pascal); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerSquareMil => As(PressureUnit.PoundForcePerSquareMil); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Torrs => As(PressureUnit.Torr); - - #endregion - - #region Static Methods - - 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[]{"торр"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PressureUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PressureUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromAtmospheres(double atmospheres) - { - double value = (double) atmospheres; - return new Pressure(value, PressureUnit.Atmosphere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromBars(double bars) - { - double value = (double) bars; - return new Pressure(value, PressureUnit.Bar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromCentibars(double centibars) - { - double value = (double) centibars; - return new Pressure(value, PressureUnit.Centibar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDecapascals(double decapascals) - { - double value = (double) decapascals; - return new Pressure(value, PressureUnit.Decapascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDecibars(double decibars) - { - double value = (double) decibars; - return new Pressure(value, PressureUnit.Decibar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromDynesPerSquareCentimeter(double dynespersquarecentimeter) - { - double value = (double) dynespersquarecentimeter; - return new Pressure(value, PressureUnit.DynePerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromFeetOfElevation(double feetofelevation) - { - double value = (double) feetofelevation; - return new Pressure(value, PressureUnit.FootOfElevation); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromFeetOfHead(double feetofhead) - { - double value = (double) feetofhead; - return new Pressure(value, PressureUnit.FootOfHead); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromGigapascals(double gigapascals) - { - double value = (double) gigapascals; - return new Pressure(value, PressureUnit.Gigapascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromHectopascals(double hectopascals) - { - double value = (double) hectopascals; - return new Pressure(value, PressureUnit.Hectopascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromInchesOfMercury(double inchesofmercury) - { - double value = (double) inchesofmercury; - return new Pressure(value, PressureUnit.InchOfMercury); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromInchesOfWaterColumn(double inchesofwatercolumn) - { - double value = (double) inchesofwatercolumn; - return new Pressure(value, PressureUnit.InchOfWaterColumn); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilobars(double kilobars) - { - double value = (double) kilobars; - return new Pressure(value, PressureUnit.Kilobar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareCentimeter(double kilogramsforcepersquarecentimeter) - { - double value = (double) kilogramsforcepersquarecentimeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareMeter(double kilogramsforcepersquaremeter) - { - double value = (double) kilogramsforcepersquaremeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilogramsForcePerSquareMillimeter(double kilogramsforcepersquaremillimeter) - { - double value = (double) kilogramsforcepersquaremillimeter; - return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareCentimeter(double kilonewtonspersquarecentimeter) - { - double value = (double) kilonewtonspersquarecentimeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareMeter(double kilonewtonspersquaremeter) - { - double value = (double) kilonewtonspersquaremeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilonewtonsPerSquareMillimeter(double kilonewtonspersquaremillimeter) - { - double value = (double) kilonewtonspersquaremillimeter; - return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopascals(double kilopascals) - { - double value = (double) kilopascals; - return new Pressure(value, PressureUnit.Kilopascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareFoot(double kilopoundsforcepersquarefoot) - { - double value = (double) kilopoundsforcepersquarefoot; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareInch(double kilopoundsforcepersquareinch) - { - double value = (double) kilopoundsforcepersquareinch; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromKilopoundsForcePerSquareMil(double kilopoundsforcepersquaremil) - { - double value = (double) kilopoundsforcepersquaremil; - return new Pressure(value, PressureUnit.KilopoundForcePerSquareMil); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMegabars(double megabars) - { - double value = (double) megabars; - return new Pressure(value, PressureUnit.Megabar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMeganewtonsPerSquareMeter(double meganewtonspersquaremeter) - { - double value = (double) meganewtonspersquaremeter; - return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMegapascals(double megapascals) - { - double value = (double) megapascals; - return new Pressure(value, PressureUnit.Megapascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMetersOfElevation(double metersofelevation) - { - double value = (double) metersofelevation; - return new Pressure(value, PressureUnit.MeterOfElevation); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMetersOfHead(double metersofhead) - { - double value = (double) metersofhead; - return new Pressure(value, PressureUnit.MeterOfHead); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMicrobars(double microbars) - { - double value = (double) microbars; - return new Pressure(value, PressureUnit.Microbar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMicropascals(double micropascals) - { - double value = (double) micropascals; - return new Pressure(value, PressureUnit.Micropascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillibars(double millibars) - { - double value = (double) millibars; - return new Pressure(value, PressureUnit.Millibar); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillimetersOfMercury(double millimetersofmercury) - { - double value = (double) millimetersofmercury; - return new Pressure(value, PressureUnit.MillimeterOfMercury); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillimeterOfWaterColumn(double millimeterofwatercolumn) - { - double value = (double) millimeterofwatercolumn; - return new Pressure(value, PressureUnit.MillimeterOfWaterColumn); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromMillipascals(double millipascals) - { - double value = (double) millipascals; - return new Pressure(value, PressureUnit.Millipascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareCentimeter(double newtonspersquarecentimeter) - { - double value = (double) newtonspersquarecentimeter; - return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareMeter(double newtonspersquaremeter) - { - double value = (double) newtonspersquaremeter; - return new Pressure(value, PressureUnit.NewtonPerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromNewtonsPerSquareMillimeter(double newtonspersquaremillimeter) - { - double value = (double) newtonspersquaremillimeter; - return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPascals(double pascals) - { - double value = (double) pascals; - return new Pressure(value, PressureUnit.Pascal); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareFoot(double poundsforcepersquarefoot) - { - double value = (double) poundsforcepersquarefoot; - return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareInch(double poundsforcepersquareinch) - { - double value = (double) poundsforcepersquareinch; - return new Pressure(value, PressureUnit.PoundForcePerSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsForcePerSquareMil(double poundsforcepersquaremil) - { - double value = (double) poundsforcepersquaremil; - return new Pressure(value, PressureUnit.PoundForcePerSquareMil); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromPoundsPerInchSecondSquared(double poundsperinchsecondsquared) - { - double value = (double) poundsperinchsecondsquared; - return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTechnicalAtmospheres(double technicalatmospheres) - { - double value = (double) technicalatmospheres; - return new Pressure(value, PressureUnit.TechnicalAtmosphere); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareCentimeter(double tonnesforcepersquarecentimeter) - { - double value = (double) tonnesforcepersquarecentimeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareMeter(double tonnesforcepersquaremeter) - { - double value = (double) tonnesforcepersquaremeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTonnesForcePerSquareMillimeter(double tonnesforcepersquaremillimeter) - { - double value = (double) tonnesforcepersquaremillimeter; - return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Pressure FromTorrs(double torrs) - { - double value = (double) torrs; - return new Pressure(value, PressureUnit.Torr); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Pressure unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Pressure From(double value, PressureUnit fromUnit) - { - return new Pressure((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Pressure Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Pressure Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Pressure result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Pressure result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PressureUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PressureUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Pressure objPressure)) throw new ArgumentException("Expected type Pressure.", nameof(obj)); - - return CompareTo(objPressure); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Pressure other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Pressure objPressure)) - return false; - - return Equals(objPressure); - } - - public bool Equals(Pressure other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Pressure within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Pressure other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Pressure. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PressureUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Pressure to another Pressure with the unit representation . - /// - /// A Pressure with the specified unit. - public Pressure ToUnit(PressureUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Pressure(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PressureUnit.Atmosphere: return _value * 1.01325 * 1e5; - case PressureUnit.Bar: return _value * 1e5; - case PressureUnit.Centibar: return (_value * 1e5) * 1e-2d; - case PressureUnit.Decapascal: return (_value) * 1e1d; - case PressureUnit.Decibar: return (_value * 1e5) * 1e-1d; - case PressureUnit.DynePerSquareCentimeter: return _value * 1.0e-1; - case PressureUnit.FootOfElevation: return Math.Pow(1.0 - (_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0; - case PressureUnit.FootOfHead: return _value * 2989.0669; - case PressureUnit.Gigapascal: return (_value) * 1e9d; - case PressureUnit.Hectopascal: return (_value) * 1e2d; - case PressureUnit.InchOfMercury: return _value / 2.95299830714159e-4; - case PressureUnit.InchOfWaterColumn: return _value * 249.08890833333; - case PressureUnit.Kilobar: return (_value * 1e5) * 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return _value * 9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return _value * 9.80665019960652; - case PressureUnit.KilogramForcePerSquareMillimeter: return _value * 9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (_value * 1e4) * 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (_value * 1e6) * 1e3d; - case PressureUnit.Kilopascal: return (_value) * 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (_value * 4.788025898033584e1) * 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (_value * 6.894757293168361e3) * 1e3d; - case PressureUnit.KilopoundForcePerSquareMil: return (_value * 6.894757293168361e9) * 1e3d; - case PressureUnit.Megabar: return (_value * 1e5) * 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (_value) * 1e6d; - case PressureUnit.Megapascal: return (_value) * 1e6d; - case PressureUnit.MeterOfElevation: return Math.Pow(1.0 - (_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0; - case PressureUnit.MeterOfHead: return _value * 9804.139432; - case PressureUnit.Microbar: return (_value * 1e5) * 1e-6d; - case PressureUnit.Micropascal: return (_value) * 1e-6d; - case PressureUnit.Millibar: return (_value * 1e5) * 1e-3d; - case PressureUnit.MillimeterOfMercury: return _value / 7.50061561302643e-3; - case PressureUnit.MillimeterOfWaterColumn: return _value * 9.806650000000272e0; - case PressureUnit.Millipascal: return (_value) * 1e-3d; - case PressureUnit.NewtonPerSquareCentimeter: return _value * 1e4; - case PressureUnit.NewtonPerSquareMeter: return _value; - case PressureUnit.NewtonPerSquareMillimeter: return _value * 1e6; - case PressureUnit.Pascal: return _value; - case PressureUnit.PoundForcePerSquareFoot: return _value * 4.788025898033584e1; - case PressureUnit.PoundForcePerSquareInch: return _value * 6.894757293168361e3; - case PressureUnit.PoundForcePerSquareMil: return _value * 6.894757293168361e9; - case PressureUnit.PoundPerInchSecondSquared: return _value * 1.785796732283465e1; - case PressureUnit.TechnicalAtmosphere: return _value * 9.80680592331 * 1e4; - case PressureUnit.TonneForcePerSquareCentimeter: return _value * 9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return _value * 9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return _value * 9.80665e9; - case PressureUnit.Torr: return _value * 1.3332266752 * 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PressureUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PressureUnit.Atmosphere: return baseUnitValue / (1.01325 * 1e5); - case PressureUnit.Bar: return baseUnitValue / 1e5; - case PressureUnit.Centibar: return (baseUnitValue / 1e5) / 1e-2d; - case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; - case PressureUnit.Decibar: return (baseUnitValue / 1e5) / 1e-1d; - case PressureUnit.DynePerSquareCentimeter: return baseUnitValue / 1.0e-1; - case PressureUnit.FootOfElevation: return (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 145366.45; - case PressureUnit.FootOfHead: return baseUnitValue * 0.000334552565551; - case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; - case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; - case PressureUnit.InchOfMercury: return baseUnitValue * 2.95299830714159e-4; - case PressureUnit.InchOfWaterColumn: return baseUnitValue / 249.08890833333; - case PressureUnit.Kilobar: return (baseUnitValue / 1e5) / 1e3d; - case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue / 9.80665e4; - case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue * 0.101971619222242; - case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue / 9.80665e6; - case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue / 1e4) / 1e3d; - case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; - case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue / 1e6) / 1e3d; - case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; - case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue / 4.788025898033584e1) / 1e3d; - case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue / 6.894757293168361e3) / 1e3d; - case PressureUnit.KilopoundForcePerSquareMil: return (baseUnitValue / 6.894757293168361e9) / 1e3d; - case PressureUnit.Megabar: return (baseUnitValue / 1e5) / 1e6d; - case PressureUnit.MeganewtonPerSquareMeter: return (baseUnitValue) / 1e6d; - case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; - case PressureUnit.MeterOfElevation: return (1.0 - Math.Pow(baseUnitValue / 101325.0, 0.190284)) * 44307.69396; - case PressureUnit.MeterOfHead: return baseUnitValue * 0.0001019977334; - case PressureUnit.Microbar: return (baseUnitValue / 1e5) / 1e-6d; - case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; - case PressureUnit.Millibar: return (baseUnitValue / 1e5) / 1e-3d; - case PressureUnit.MillimeterOfMercury: return baseUnitValue * 7.50061561302643e-3; - case PressureUnit.MillimeterOfWaterColumn: return baseUnitValue / 9.806650000000272e0; - case PressureUnit.Millipascal: return (baseUnitValue) / 1e-3d; - case PressureUnit.NewtonPerSquareCentimeter: return baseUnitValue / 1e4; - case PressureUnit.NewtonPerSquareMeter: return baseUnitValue; - case PressureUnit.NewtonPerSquareMillimeter: return baseUnitValue / 1e6; - case PressureUnit.Pascal: return baseUnitValue; - case PressureUnit.PoundForcePerSquareFoot: return baseUnitValue / 4.788025898033584e1; - case PressureUnit.PoundForcePerSquareInch: return baseUnitValue / 6.894757293168361e3; - case PressureUnit.PoundForcePerSquareMil: return baseUnitValue / 6.894757293168361e9; - case PressureUnit.PoundPerInchSecondSquared: return baseUnitValue / 1.785796732283465e1; - case PressureUnit.TechnicalAtmosphere: return baseUnitValue / (9.80680592331 * 1e4); - case PressureUnit.TonneForcePerSquareCentimeter: return baseUnitValue / 9.80665e7; - case PressureUnit.TonneForcePerSquareMeter: return baseUnitValue / 9.80665e3; - case PressureUnit.TonneForcePerSquareMillimeter: return baseUnitValue / 9.80665e9; - case PressureUnit.Torr: return baseUnitValue / (1.3332266752 * 1e2); - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.g.cs deleted file mode 100644 index 2259575ad1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ /dev/null @@ -1,854 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class PressureChangeRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly PressureChangeRateUnit? _unit; - - static PressureChangeRate() - { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - BaseUnit = PressureChangeRateUnit.PascalPerSecond; - MaxValue = new PressureChangeRate(double.MaxValue, BaseUnit); - MinValue = new PressureChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.PressureChangeRate; - Units = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); - Zero = new PressureChangeRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.PressureChangeRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit PascalPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public PressureChangeRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private PressureChangeRate(double value, PressureChangeRateUnit unit) - { - if (unit == PressureChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. - /// - public static PressureChangeRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of PressureChangeRate - /// - public static PressureChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of PressureChangeRate - /// - public static PressureChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the PressureChangeRate quantity. - /// - public static PressureChangeRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. - /// - public static PressureChangeRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => PressureChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopascalsPerMinute => As(PressureChangeRateUnit.KilopascalPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapascalsPerMinute => As(PressureChangeRateUnit.MegapascalPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersOfMercuryPerSecond => As(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PascalsPerMinute => As(PressureChangeRateUnit.PascalPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); - - #endregion - - #region Static Methods - - 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²/с"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(PressureChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromAtmospheresPerSecond(double atmospherespersecond) - { - double value = (double) atmospherespersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromKilopascalsPerMinute(double kilopascalsperminute) - { - double value = (double) kilopascalsperminute; - return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromKilopascalsPerSecond(double kilopascalspersecond) - { - double value = (double) kilopascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(double kilopoundsforcepersquareinchperminute) - { - double value = (double) kilopoundsforcepersquareinchperminute; - return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(double kilopoundsforcepersquareinchpersecond) - { - double value = (double) kilopoundsforcepersquareinchpersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMegapascalsPerMinute(double megapascalsperminute) - { - double value = (double) megapascalsperminute; - return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMegapascalsPerSecond(double megapascalspersecond) - { - double value = (double) megapascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(double megapoundsforcepersquareinchperminute) - { - double value = (double) megapoundsforcepersquareinchperminute; - return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(double megapoundsforcepersquareinchpersecond) - { - double value = (double) megapoundsforcepersquareinchpersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromMillimetersOfMercuryPerSecond(double millimetersofmercurypersecond) - { - double value = (double) millimetersofmercurypersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.MillimeterOfMercuryPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromPascalsPerMinute(double pascalsperminute) - { - double value = (double) pascalsperminute; - return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromPascalsPerSecond(double pascalspersecond) - { - double value = (double) pascalspersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(double poundsforcepersquareinchperminute) - { - double value = (double) poundsforcepersquareinchperminute; - return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(double poundsforcepersquareinchpersecond) - { - double value = (double) poundsforcepersquareinchpersecond; - return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// PressureChangeRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static PressureChangeRate From(double value, PressureChangeRateUnit fromUnit) - { - return new PressureChangeRate((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static PressureChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PressureChangeRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out PressureChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out PressureChangeRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static PressureChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out PressureChangeRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PressureChangeRate objPressureChangeRate)) throw new ArgumentException("Expected type PressureChangeRate.", nameof(obj)); - - return CompareTo(objPressureChangeRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(PressureChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is PressureChangeRate objPressureChangeRate)) - return false; - - return Equals(objPressureChangeRate); - } - - public bool Equals(PressureChangeRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another PressureChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(PressureChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PressureChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((PressureChangeRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureChangeRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . - /// - /// A PressureChangeRate with the specified unit. - public PressureChangeRate ToUnit(PressureChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new PressureChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325 * 1e5; - case PressureChangeRateUnit.KilopascalPerMinute: return (_value / 60) * 1e3d; - case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute: return (_value * 6.894757293168361e3 / 60) * 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond: return (_value * 6.894757293168361e3) * 1e3d; - case PressureChangeRateUnit.MegapascalPerMinute: return (_value / 60) * 1e6d; - case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute: return (_value * 6.894757293168361e3 / 60) * 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond: return (_value * 6.894757293168361e3) * 1e6d; - case PressureChangeRateUnit.MillimeterOfMercuryPerSecond: return _value * 133.322; - case PressureChangeRateUnit.PascalPerMinute: return _value / 60; - case PressureChangeRateUnit.PascalPerSecond: return _value; - case PressureChangeRateUnit.PoundForcePerSquareInchPerMinute: return _value * 6.894757293168361e3 / 60; - case PressureChangeRateUnit.PoundForcePerSquareInchPerSecond: return _value * 6.894757293168361e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(PressureChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325 * 1e5); - case PressureChangeRateUnit.KilopascalPerMinute: return (baseUnitValue * 60) / 1e3d; - case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute: return (baseUnitValue / 6.894757293168361e3 * 60) / 1e3d; - case PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond: return (baseUnitValue / 6.894757293168361e3) / 1e3d; - case PressureChangeRateUnit.MegapascalPerMinute: return (baseUnitValue * 60) / 1e6d; - case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute: return (baseUnitValue / 6.894757293168361e3 * 60) / 1e6d; - case PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond: return (baseUnitValue / 6.894757293168361e3) / 1e6d; - case PressureChangeRateUnit.MillimeterOfMercuryPerSecond: return baseUnitValue / 133.322; - case PressureChangeRateUnit.PascalPerMinute: return baseUnitValue * 60; - case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; - case PressureChangeRateUnit.PoundForcePerSquareInchPerMinute: return baseUnitValue / 6.894757293168361e3 * 60; - case PressureChangeRateUnit.PoundForcePerSquareInchPerSecond: return baseUnitValue / 6.894757293168361e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.g.cs deleted file mode 100644 index e31ad3a46f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Ratio.g.cs +++ /dev/null @@ -1,688 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Ratio : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RatioUnit? _unit; - - static Ratio() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = RatioUnit.DecimalFraction; - MaxValue = new Ratio(double.MaxValue, BaseUnit); - MinValue = new Ratio(double.MinValue, BaseUnit); - QuantityType = QuantityType.Ratio; - Units = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); - Zero = new Ratio(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Ratio, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DecimalFraction. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Ratio() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Ratio(double value, RatioUnit unit) - { - if (unit == RatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. - /// - public static RatioUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Ratio - /// - public static Ratio MaxValue { get; } - - /// - /// Represents the smallest possible value of Ratio - /// - public static Ratio MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Ratio quantity. - /// - public static RatioUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. - /// - public static Ratio Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Ratio.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Ratio.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DecimalFractions => As(RatioUnit.DecimalFraction); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerBillion => As(RatioUnit.PartPerBillion); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerMillion => As(RatioUnit.PartPerMillion); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerThousand => As(RatioUnit.PartPerThousand); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); - - /// - /// Gets a value of this quantity converted into - /// - public double Percent => As(RatioUnit.Percent); - - #endregion - - #region Static Methods - - 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[]{"%"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RatioUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RatioUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromDecimalFractions(double decimalfractions) - { - double value = (double) decimalfractions; - return new Ratio(value, RatioUnit.DecimalFraction); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerBillion(double partsperbillion) - { - double value = (double) partsperbillion; - return new Ratio(value, RatioUnit.PartPerBillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerMillion(double partspermillion) - { - double value = (double) partspermillion; - return new Ratio(value, RatioUnit.PartPerMillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerThousand(double partsperthousand) - { - double value = (double) partsperthousand; - return new Ratio(value, RatioUnit.PartPerThousand); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPartsPerTrillion(double partspertrillion) - { - double value = (double) partspertrillion; - return new Ratio(value, RatioUnit.PartPerTrillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Ratio FromPercent(double percent) - { - double value = (double) percent; - return new Ratio(value, RatioUnit.Percent); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Ratio unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Ratio From(double value, RatioUnit fromUnit) - { - return new Ratio((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Ratio Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Ratio Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Ratio result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Ratio result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RatioUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RatioUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RatioUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Ratio objRatio)) throw new ArgumentException("Expected type Ratio.", nameof(obj)); - - return CompareTo(objRatio); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Ratio other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Ratio objRatio)) - return false; - - return Equals(objRatio); - } - - public bool Equals(Ratio other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Ratio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Ratio. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RatioUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Ratio to another Ratio with the unit representation . - /// - /// A Ratio with the specified unit. - public Ratio ToUnit(RatioUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Ratio(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RatioUnit.DecimalFraction: return _value; - case RatioUnit.PartPerBillion: return _value / 1e9; - case RatioUnit.PartPerMillion: return _value / 1e6; - case RatioUnit.PartPerThousand: return _value / 1e3; - case RatioUnit.PartPerTrillion: return _value / 1e12; - case RatioUnit.Percent: return _value / 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RatioUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RatioUnit.DecimalFraction: return baseUnitValue; - case RatioUnit.PartPerBillion: return baseUnitValue * 1e9; - case RatioUnit.PartPerMillion: return baseUnitValue * 1e6; - case RatioUnit.PartPerThousand: return baseUnitValue * 1e3; - case RatioUnit.PartPerTrillion: return baseUnitValue * 1e12; - case RatioUnit.Percent: return baseUnitValue * 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RatioChangeRate.g.cs deleted file mode 100644 index 3b0137a5bf..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ /dev/null @@ -1,612 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The change in ratio per unit of time. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RatioChangeRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RatioChangeRateUnit? _unit; - - static RatioChangeRate() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = RatioChangeRateUnit.DecimalFractionPerSecond; - MaxValue = new RatioChangeRate(double.MaxValue, BaseUnit); - MinValue = new RatioChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.RatioChangeRate; - Units = Enum.GetValues(typeof(RatioChangeRateUnit)).Cast().Except(new RatioChangeRateUnit[]{ RatioChangeRateUnit.Undefined }).ToArray(); - Zero = new RatioChangeRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.RatioChangeRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DecimalFractionPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public RatioChangeRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private RatioChangeRate(double value, RatioChangeRateUnit unit) - { - if (unit == RatioChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of RatioChangeRate, which is DecimalFractionPerSecond. All conversions go via this value. - /// - public static RatioChangeRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of RatioChangeRate - /// - public static RatioChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of RatioChangeRate - /// - public static RatioChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the RatioChangeRate quantity. - /// - public static RatioChangeRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFractionPerSecond. - /// - public static RatioChangeRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RatioChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => RatioChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RatioChangeRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DecimalFractionsPerSecond => As(RatioChangeRateUnit.DecimalFractionPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PercentsPerSecond => As(RatioChangeRateUnit.PercentPerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RatioChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RatioChangeRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RatioChangeRate FromDecimalFractionsPerSecond(double decimalfractionspersecond) - { - double value = (double) decimalfractionspersecond; - return new RatioChangeRate(value, RatioChangeRateUnit.DecimalFractionPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RatioChangeRate FromPercentsPerSecond(double percentspersecond) - { - double value = (double) percentspersecond; - return new RatioChangeRate(value, RatioChangeRateUnit.PercentPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RatioChangeRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RatioChangeRate From(double value, RatioChangeRateUnit fromUnit) - { - return new RatioChangeRate((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RatioChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RatioChangeRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RatioChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out RatioChangeRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RatioChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RatioChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RatioChangeRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RatioChangeRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RatioChangeRate objRatioChangeRate)) throw new ArgumentException("Expected type RatioChangeRate.", nameof(obj)); - - return CompareTo(objRatioChangeRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(RatioChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is RatioChangeRate objRatioChangeRate)) - return false; - - return Equals(objRatioChangeRate); - } - - public bool Equals(RatioChangeRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RatioChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RatioChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RatioChangeRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioChangeRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RatioChangeRate to another RatioChangeRate with the unit representation . - /// - /// A RatioChangeRate with the specified unit. - public RatioChangeRate ToUnit(RatioChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RatioChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RatioChangeRateUnit.DecimalFractionPerSecond: return _value; - case RatioChangeRateUnit.PercentPerSecond: return _value / 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RatioChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RatioChangeRateUnit.DecimalFractionPerSecond: return baseUnitValue; - case RatioChangeRateUnit.PercentPerSecond: return baseUnitValue * 1e2; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.g.cs deleted file mode 100644 index b02143fcc6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ReactiveEnergy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReactiveEnergyUnit? _unit; - - static ReactiveEnergy() - { - BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); - BaseUnit = ReactiveEnergyUnit.VoltampereReactiveHour; - MaxValue = new ReactiveEnergy(double.MaxValue, BaseUnit); - MinValue = new ReactiveEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReactiveEnergy; - Units = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); - Zero = new ReactiveEnergy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ReactiveEnergy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltampereReactiveHour. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ReactiveEnergy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ReactiveEnergy(double value, ReactiveEnergyUnit unit) - { - if (unit == ReactiveEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. - /// - public static ReactiveEnergyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ReactiveEnergy - /// - public static ReactiveEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of ReactiveEnergy - /// - public static ReactiveEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ReactiveEnergy quantity. - /// - public static ReactiveEnergyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. - /// - public static ReactiveEnergy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ReactiveEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ReactiveEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromKilovoltampereReactiveHours(double kilovoltamperereactivehours) - { - double value = (double) kilovoltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromMegavoltampereReactiveHours(double megavoltamperereactivehours) - { - double value = (double) megavoltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactiveEnergy FromVoltampereReactiveHours(double voltamperereactivehours) - { - double value = (double) voltamperereactivehours; - return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReactiveEnergy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) - { - return new ReactiveEnergy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReactiveEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReactiveEnergy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ReactiveEnergy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactiveEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ReactiveEnergyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ReactiveEnergy objReactiveEnergy)) throw new ArgumentException("Expected type ReactiveEnergy.", nameof(obj)); - - return CompareTo(objReactiveEnergy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ReactiveEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReactiveEnergy objReactiveEnergy)) - return false; - - return Equals(objReactiveEnergy); - } - - public bool Equals(ReactiveEnergy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ReactiveEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReactiveEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReactiveEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ReactiveEnergyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactiveEnergyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation . - /// - /// A ReactiveEnergy with the specified unit. - public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReactiveEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (_value) * 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (_value) * 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReactiveEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (baseUnitValue) / 1e3d; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (baseUnitValue) / 1e6d; - case ReactiveEnergyUnit.VoltampereReactiveHour: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.g.cs deleted file mode 100644 index 2ba8d48483..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReactivePower.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ReactivePower : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReactivePowerUnit? _unit; - - static ReactivePower() - { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = ReactivePowerUnit.VoltampereReactive; - MaxValue = new ReactivePower(double.MaxValue, BaseUnit); - MinValue = new ReactivePower(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReactivePower; - Units = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); - Zero = new ReactivePower(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ReactivePower, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit VoltampereReactive. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ReactivePower() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ReactivePower(double value, ReactivePowerUnit unit) - { - if (unit == ReactivePowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. - /// - public static ReactivePowerUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ReactivePower - /// - public static ReactivePower MaxValue { get; } - - /// - /// Represents the smallest possible value of ReactivePower - /// - public static ReactivePower MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ReactivePower quantity. - /// - public static ReactivePowerUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. - /// - public static ReactivePower Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ReactivePower.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReactivePower.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); - - /// - /// Gets a value of this quantity converted into - /// - public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); - - /// - /// Gets a value of this quantity converted into - /// - public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); - - /// - /// Gets a value of this quantity converted into - /// - public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ReactivePowerUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromGigavoltamperesReactive(double gigavoltamperesreactive) - { - double value = (double) gigavoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromKilovoltamperesReactive(double kilovoltamperesreactive) - { - double value = (double) kilovoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromMegavoltamperesReactive(double megavoltamperesreactive) - { - double value = (double) megavoltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReactivePower FromVoltamperesReactive(double voltamperesreactive) - { - double value = (double) voltamperesreactive; - return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReactivePower unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReactivePower From(double value, ReactivePowerUnit fromUnit) - { - return new ReactivePower((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReactivePower Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReactivePower Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReactivePower result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ReactivePower result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReactivePowerUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReactivePowerUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ReactivePowerUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ReactivePowerUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ReactivePower objReactivePower)) throw new ArgumentException("Expected type ReactivePower.", nameof(obj)); - - return CompareTo(objReactivePower); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ReactivePower other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReactivePower objReactivePower)) - return false; - - return Equals(objReactivePower); - } - - public bool Equals(ReactivePower other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ReactivePower within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ReactivePower other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReactivePower. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ReactivePowerUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReactivePowerUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReactivePower to another ReactivePower with the unit representation . - /// - /// A ReactivePower with the specified unit. - public ReactivePower ToUnit(ReactivePowerUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReactivePower(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (_value) * 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (_value) * 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (_value) * 1e6d; - case ReactivePowerUnit.VoltampereReactive: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReactivePowerUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReactivePowerUnit.GigavoltampereReactive: return (baseUnitValue) / 1e9d; - case ReactivePowerUnit.KilovoltampereReactive: return (baseUnitValue) / 1e3d; - case ReactivePowerUnit.MegavoltampereReactive: return (baseUnitValue) / 1e6d; - case ReactivePowerUnit.VoltampereReactive: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReciprocalArea.g.cs deleted file mode 100644 index 0db340c906..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ /dev/null @@ -1,786 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Reciprocal area (Inverse-square) quantity is used to specify a physical quantity inversely proportional to the square of the distance. - /// - /// - /// https://en.wikipedia.org/wiki/Inverse-square_law - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ReciprocalArea : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReciprocalAreaUnit? _unit; - - static ReciprocalArea() - { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); - BaseUnit = ReciprocalAreaUnit.InverseSquareMeter; - MaxValue = new ReciprocalArea(double.MaxValue, BaseUnit); - MinValue = new ReciprocalArea(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReciprocalArea; - Units = Enum.GetValues(typeof(ReciprocalAreaUnit)).Cast().Except(new ReciprocalAreaUnit[]{ ReciprocalAreaUnit.Undefined }).ToArray(); - Zero = new ReciprocalArea(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ReciprocalArea, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit InverseSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ReciprocalArea() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ReciprocalArea(double value, ReciprocalAreaUnit unit) - { - if (unit == ReciprocalAreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ReciprocalArea, which is InverseSquareMeter. All conversions go via this value. - /// - public static ReciprocalAreaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ReciprocalArea - /// - public static ReciprocalArea MaxValue { get; } - - /// - /// Represents the smallest possible value of ReciprocalArea - /// - public static ReciprocalArea MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ReciprocalArea quantity. - /// - public static ReciprocalAreaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InverseSquareMeter. - /// - public static ReciprocalArea Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReciprocalAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ReciprocalArea.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReciprocalArea.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareCentimeters => As(ReciprocalAreaUnit.InverseSquareCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareDecimeters => As(ReciprocalAreaUnit.InverseSquareDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareFeet => As(ReciprocalAreaUnit.InverseSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareInches => As(ReciprocalAreaUnit.InverseSquareInch); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareKilometers => As(ReciprocalAreaUnit.InverseSquareKilometer); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareMeters => As(ReciprocalAreaUnit.InverseSquareMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareMicrometers => As(ReciprocalAreaUnit.InverseSquareMicrometer); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareMiles => As(ReciprocalAreaUnit.InverseSquareMile); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareMillimeters => As(ReciprocalAreaUnit.InverseSquareMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseSquareYards => As(ReciprocalAreaUnit.InverseSquareYard); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseUsSurveySquareFeet => As(ReciprocalAreaUnit.InverseUsSurveySquareFoot); - - #endregion - - #region Static Methods - - 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)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ReciprocalAreaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ReciprocalAreaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareCentimeters(double inversesquarecentimeters) - { - double value = (double) inversesquarecentimeters; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareDecimeters(double inversesquaredecimeters) - { - double value = (double) inversesquaredecimeters; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareFeet(double inversesquarefeet) - { - double value = (double) inversesquarefeet; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareInches(double inversesquareinches) - { - double value = (double) inversesquareinches; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareKilometers(double inversesquarekilometers) - { - double value = (double) inversesquarekilometers; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareKilometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareMeters(double inversesquaremeters) - { - double value = (double) inversesquaremeters; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareMicrometers(double inversesquaremicrometers) - { - double value = (double) inversesquaremicrometers; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMicrometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareMiles(double inversesquaremiles) - { - double value = (double) inversesquaremiles; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareMillimeters(double inversesquaremillimeters) - { - double value = (double) inversesquaremillimeters; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseSquareYards(double inversesquareyards) - { - double value = (double) inversesquareyards; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareYard); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalArea FromInverseUsSurveySquareFeet(double inverseussurveysquarefeet) - { - double value = (double) inverseussurveysquarefeet; - return new ReciprocalArea(value, ReciprocalAreaUnit.InverseUsSurveySquareFoot); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReciprocalArea unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReciprocalArea From(double value, ReciprocalAreaUnit fromUnit) - { - return new ReciprocalArea((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReciprocalArea Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReciprocalArea Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReciprocalArea result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ReciprocalArea result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReciprocalAreaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReciprocalAreaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ReciprocalAreaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ReciprocalAreaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ReciprocalArea objReciprocalArea)) throw new ArgumentException("Expected type ReciprocalArea.", nameof(obj)); - - return CompareTo(objReciprocalArea); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ReciprocalArea other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReciprocalArea objReciprocalArea)) - return false; - - return Equals(objReciprocalArea); - } - - public bool Equals(ReciprocalArea other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ReciprocalArea within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReciprocalArea. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ReciprocalAreaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReciprocalAreaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReciprocalArea to another ReciprocalArea with the unit representation . - /// - /// A ReciprocalArea with the specified unit. - public ReciprocalArea ToUnit(ReciprocalAreaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReciprocalArea(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ReciprocalAreaUnit.InverseSquareCentimeter: return _value / 1e-4; - case ReciprocalAreaUnit.InverseSquareDecimeter: return _value / 1e-2; - case ReciprocalAreaUnit.InverseSquareFoot: return _value / 0.092903; - case ReciprocalAreaUnit.InverseSquareInch: return _value / 0.00064516; - case ReciprocalAreaUnit.InverseSquareKilometer: return _value / 1e6; - case ReciprocalAreaUnit.InverseSquareMeter: return _value; - case ReciprocalAreaUnit.InverseSquareMicrometer: return _value / 1e-12; - case ReciprocalAreaUnit.InverseSquareMile: return _value / 2.59e6; - case ReciprocalAreaUnit.InverseSquareMillimeter: return _value / 1e-6; - case ReciprocalAreaUnit.InverseSquareYard: return _value / 0.836127; - case ReciprocalAreaUnit.InverseUsSurveySquareFoot: return _value / 0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReciprocalAreaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReciprocalAreaUnit.InverseSquareCentimeter: return baseUnitValue * 1e-4; - case ReciprocalAreaUnit.InverseSquareDecimeter: return baseUnitValue * 1e-2; - case ReciprocalAreaUnit.InverseSquareFoot: return baseUnitValue * 0.092903; - case ReciprocalAreaUnit.InverseSquareInch: return baseUnitValue * 0.00064516; - case ReciprocalAreaUnit.InverseSquareKilometer: return baseUnitValue * 1e6; - case ReciprocalAreaUnit.InverseSquareMeter: return baseUnitValue; - case ReciprocalAreaUnit.InverseSquareMicrometer: return baseUnitValue * 1e-12; - case ReciprocalAreaUnit.InverseSquareMile: return baseUnitValue * 2.59e6; - case ReciprocalAreaUnit.InverseSquareMillimeter: return baseUnitValue * 1e-6; - case ReciprocalAreaUnit.InverseSquareYard: return baseUnitValue * 0.836127; - case ReciprocalAreaUnit.InverseUsSurveySquareFoot: return baseUnitValue * 0.09290341161; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReciprocalLength.g.cs deleted file mode 100644 index 643882e320..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ /dev/null @@ -1,767 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Reciprocal (Inverse) Length is used in various fields of science and mathematics. It is defined as the inverse value of a length unit. - /// - /// - /// https://en.wikipedia.org/wiki/Reciprocal_length - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ReciprocalLength : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ReciprocalLengthUnit? _unit; - - static ReciprocalLength() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 0, 0, 0); - BaseUnit = ReciprocalLengthUnit.InverseMeter; - MaxValue = new ReciprocalLength(double.MaxValue, BaseUnit); - MinValue = new ReciprocalLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReciprocalLength; - Units = Enum.GetValues(typeof(ReciprocalLengthUnit)).Cast().Except(new ReciprocalLengthUnit[]{ ReciprocalLengthUnit.Undefined }).ToArray(); - Zero = new ReciprocalLength(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ReciprocalLength, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit InverseMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ReciprocalLength() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ReciprocalLength(double value, ReciprocalLengthUnit unit) - { - if (unit == ReciprocalLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ReciprocalLength, which is InverseMeter. All conversions go via this value. - /// - public static ReciprocalLengthUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ReciprocalLength - /// - public static ReciprocalLength MaxValue { get; } - - /// - /// Represents the smallest possible value of ReciprocalLength - /// - public static ReciprocalLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ReciprocalLength quantity. - /// - public static ReciprocalLengthUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InverseMeter. - /// - public static ReciprocalLength Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ReciprocalLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ReciprocalLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ReciprocalLength.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double InverseCentimeters => As(ReciprocalLengthUnit.InverseCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseFeet => As(ReciprocalLengthUnit.InverseFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseInches => As(ReciprocalLengthUnit.InverseInch); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMeters => As(ReciprocalLengthUnit.InverseMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMicroinches => As(ReciprocalLengthUnit.InverseMicroinch); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMils => As(ReciprocalLengthUnit.InverseMil); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMiles => As(ReciprocalLengthUnit.InverseMile); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseMillimeters => As(ReciprocalLengthUnit.InverseMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseUsSurveyFeet => As(ReciprocalLengthUnit.InverseUsSurveyFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double InverseYards => As(ReciprocalLengthUnit.InverseYard); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ReciprocalLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ReciprocalLengthUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseCentimeters(double inversecentimeters) - { - double value = (double) inversecentimeters; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseFeet(double inversefeet) - { - double value = (double) inversefeet; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseInches(double inverseinches) - { - double value = (double) inverseinches; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseMeters(double inversemeters) - { - double value = (double) inversemeters; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseMicroinches(double inversemicroinches) - { - double value = (double) inversemicroinches; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMicroinch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseMils(double inversemils) - { - double value = (double) inversemils; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMil); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseMiles(double inversemiles) - { - double value = (double) inversemiles; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseMillimeters(double inversemillimeters) - { - double value = (double) inversemillimeters; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseUsSurveyFeet(double inverseussurveyfeet) - { - double value = (double) inverseussurveyfeet; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseUsSurveyFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ReciprocalLength FromInverseYards(double inverseyards) - { - double value = (double) inverseyards; - return new ReciprocalLength(value, ReciprocalLengthUnit.InverseYard); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ReciprocalLength unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ReciprocalLength From(double value, ReciprocalLengthUnit fromUnit) - { - return new ReciprocalLength((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ReciprocalLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReciprocalLength Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ReciprocalLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ReciprocalLength result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ReciprocalLengthUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ReciprocalLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ReciprocalLengthUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ReciprocalLengthUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ReciprocalLength objReciprocalLength)) throw new ArgumentException("Expected type ReciprocalLength.", nameof(obj)); - - return CompareTo(objReciprocalLength); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ReciprocalLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReciprocalLength objReciprocalLength)) - return false; - - return Equals(objReciprocalLength); - } - - public bool Equals(ReciprocalLength other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ReciprocalLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReciprocalLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ReciprocalLengthUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReciprocalLengthUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ReciprocalLength to another ReciprocalLength with the unit representation . - /// - /// A ReciprocalLength with the specified unit. - public ReciprocalLength ToUnit(ReciprocalLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ReciprocalLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ReciprocalLengthUnit.InverseCentimeter: return _value * 1e2; - case ReciprocalLengthUnit.InverseFoot: return _value / 0.3048; - case ReciprocalLengthUnit.InverseInch: return _value / 2.54e-2; - case ReciprocalLengthUnit.InverseMeter: return _value; - case ReciprocalLengthUnit.InverseMicroinch: return _value / 2.54e-8; - case ReciprocalLengthUnit.InverseMil: return _value / 2.54e-5; - case ReciprocalLengthUnit.InverseMile: return _value / 1609.34; - case ReciprocalLengthUnit.InverseMillimeter: return _value * 1e3; - case ReciprocalLengthUnit.InverseUsSurveyFoot: return _value * 3937 / 1200; - case ReciprocalLengthUnit.InverseYard: return _value / 0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ReciprocalLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ReciprocalLengthUnit.InverseCentimeter: return baseUnitValue / 1e2; - case ReciprocalLengthUnit.InverseFoot: return baseUnitValue * 0.3048; - case ReciprocalLengthUnit.InverseInch: return baseUnitValue * 2.54e-2; - case ReciprocalLengthUnit.InverseMeter: return baseUnitValue; - case ReciprocalLengthUnit.InverseMicroinch: return baseUnitValue * 2.54e-8; - case ReciprocalLengthUnit.InverseMil: return baseUnitValue * 2.54e-5; - case ReciprocalLengthUnit.InverseMile: return baseUnitValue * 1609.34; - case ReciprocalLengthUnit.InverseMillimeter: return baseUnitValue / 1e3; - case ReciprocalLengthUnit.InverseUsSurveyFoot: return baseUnitValue * 1200 / 3937; - case ReciprocalLengthUnit.InverseYard: return baseUnitValue * 0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RelativeHumidity.g.cs deleted file mode 100644 index 062e589d67..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ /dev/null @@ -1,593 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RelativeHumidity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RelativeHumidityUnit? _unit; - - static RelativeHumidity() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = RelativeHumidityUnit.Percent; - MaxValue = new RelativeHumidity(double.MaxValue, BaseUnit); - MinValue = new RelativeHumidity(double.MinValue, BaseUnit); - QuantityType = QuantityType.RelativeHumidity; - Units = Enum.GetValues(typeof(RelativeHumidityUnit)).Cast().Except(new RelativeHumidityUnit[]{ RelativeHumidityUnit.Undefined }).ToArray(); - Zero = new RelativeHumidity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.RelativeHumidity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Percent. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public RelativeHumidity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private RelativeHumidity(double value, RelativeHumidityUnit unit) - { - if (unit == RelativeHumidityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of RelativeHumidity, which is Percent. All conversions go via this value. - /// - public static RelativeHumidityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of RelativeHumidity - /// - public static RelativeHumidity MaxValue { get; } - - /// - /// Represents the smallest possible value of RelativeHumidity - /// - public static RelativeHumidity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the RelativeHumidity quantity. - /// - public static RelativeHumidityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Percent. - /// - public static RelativeHumidity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RelativeHumidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => RelativeHumidity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RelativeHumidity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Percent => As(RelativeHumidityUnit.Percent); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(RelativeHumidityUnit.Percent, new CultureInfo("en-US"), false, true, new string[]{"%RH"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RelativeHumidityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RelativeHumidityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RelativeHumidity FromPercent(double percent) - { - double value = (double) percent; - return new RelativeHumidity(value, RelativeHumidityUnit.Percent); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RelativeHumidity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RelativeHumidity From(double value, RelativeHumidityUnit fromUnit) - { - return new RelativeHumidity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RelativeHumidity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RelativeHumidity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RelativeHumidity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out RelativeHumidity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RelativeHumidityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RelativeHumidityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RelativeHumidityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RelativeHumidityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RelativeHumidity objRelativeHumidity)) throw new ArgumentException("Expected type RelativeHumidity.", nameof(obj)); - - return CompareTo(objRelativeHumidity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(RelativeHumidity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is RelativeHumidity objRelativeHumidity)) - return false; - - return Equals(objRelativeHumidity); - } - - public bool Equals(RelativeHumidity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RelativeHumidity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RelativeHumidity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RelativeHumidityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RelativeHumidityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RelativeHumidity to another RelativeHumidity with the unit representation . - /// - /// A RelativeHumidity with the specified unit. - public RelativeHumidity ToUnit(RelativeHumidityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RelativeHumidity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RelativeHumidityUnit.Percent: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RelativeHumidityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RelativeHumidityUnit.Percent: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.g.cs deleted file mode 100644 index 52e54d14fb..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Angular acceleration is the rate of change of rotational speed. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalAcceleration : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalAccelerationUnit? _unit; - - static RotationalAcceleration() - { - BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); - BaseUnit = RotationalAccelerationUnit.RadianPerSecondSquared; - MaxValue = new RotationalAcceleration(double.MaxValue, BaseUnit); - MinValue = new RotationalAcceleration(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalAcceleration; - Units = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); - Zero = new RotationalAcceleration(0, BaseUnit); - Info = new QuantityInfo(QuantityType.RotationalAcceleration, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit RadianPerSecondSquared. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public RotationalAcceleration() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private RotationalAcceleration(double value, RotationalAccelerationUnit unit) - { - if (unit == RotationalAccelerationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. - /// - public static RotationalAccelerationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of RotationalAcceleration - /// - public static RotationalAcceleration MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalAcceleration - /// - public static RotationalAcceleration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the RotationalAcceleration quantity. - /// - public static RotationalAccelerationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. - /// - public static RotationalAcceleration Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => RotationalAcceleration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); - - /// - /// Gets a value of this quantity converted into - /// - public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double RevolutionsPerSecondSquared => As(RotationalAccelerationUnit.RevolutionPerSecondSquared); - - #endregion - - #region Static Methods - - 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²"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RotationalAccelerationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromDegreesPerSecondSquared(double degreespersecondsquared) - { - double value = (double) degreespersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRadiansPerSecondSquared(double radianspersecondsquared) - { - double value = (double) radianspersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double revolutionsperminutepersecond) - { - double value = (double) revolutionsperminutepersecond; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalAcceleration FromRevolutionsPerSecondSquared(double revolutionspersecondsquared) - { - double value = (double) revolutionspersecondsquared; - return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerSecondSquared); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalAcceleration unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalAcceleration From(double value, RotationalAccelerationUnit fromUnit) - { - return new RotationalAcceleration((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalAcceleration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalAcceleration Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalAcceleration result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out RotationalAcceleration result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalAccelerationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RotationalAccelerationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalAcceleration objRotationalAcceleration)) throw new ArgumentException("Expected type RotationalAcceleration.", nameof(obj)); - - return CompareTo(objRotationalAcceleration); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(RotationalAcceleration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalAcceleration objRotationalAcceleration)) - return false; - - return Equals(objRotationalAcceleration); - } - - public bool Equals(RotationalAcceleration other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalAcceleration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalAcceleration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalAcceleration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RotationalAccelerationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalAccelerationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . - /// - /// A RotationalAcceleration with the specified unit. - public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalAcceleration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI / 180) * _value; - case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2 * Math.PI) / 60) * _value; - case RotationalAccelerationUnit.RevolutionPerSecondSquared: return (2 * Math.PI) * _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalAccelerationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: return (180 / Math.PI) * baseUnitValue; - case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60 / (2 * Math.PI)) * baseUnitValue; - case RotationalAccelerationUnit.RevolutionPerSecondSquared: return (1 / (2 * Math.PI)) * baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.g.cs deleted file mode 100644 index 30d463a633..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ /dev/null @@ -1,833 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalSpeed : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalSpeedUnit? _unit; - - static RotationalSpeed() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = RotationalSpeedUnit.RadianPerSecond; - MaxValue = new RotationalSpeed(double.MaxValue, BaseUnit); - MinValue = new RotationalSpeed(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalSpeed; - Units = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); - Zero = new RotationalSpeed(0, BaseUnit); - Info = new QuantityInfo(QuantityType.RotationalSpeed, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit RadianPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public RotationalSpeed() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private RotationalSpeed(double value, RotationalSpeedUnit unit) - { - if (unit == RotationalSpeedUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. - /// - public static RotationalSpeedUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of RotationalSpeed - /// - public static RotationalSpeed MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalSpeed - /// - public static RotationalSpeed MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the RotationalSpeed quantity. - /// - public static RotationalSpeedUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. - /// - public static RotationalSpeed Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => RotationalSpeed.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); - - #endregion - - #region Static Methods - - 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[]{"об/с"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RotationalSpeedUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromCentiradiansPerSecond(double centiradianspersecond) - { - double value = (double) centiradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDeciradiansPerSecond(double deciradianspersecond) - { - double value = (double) deciradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDegreesPerMinute(double degreesperminute) - { - double value = (double) degreesperminute; - return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromDegreesPerSecond(double degreespersecond) - { - double value = (double) degreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMicrodegreesPerSecond(double microdegreespersecond) - { - double value = (double) microdegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMicroradiansPerSecond(double microradianspersecond) - { - double value = (double) microradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMillidegreesPerSecond(double millidegreespersecond) - { - double value = (double) millidegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromMilliradiansPerSecond(double milliradianspersecond) - { - double value = (double) milliradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromNanodegreesPerSecond(double nanodegreespersecond) - { - double value = (double) nanodegreespersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromNanoradiansPerSecond(double nanoradianspersecond) - { - double value = (double) nanoradianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRadiansPerSecond(double radianspersecond) - { - double value = (double) radianspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRevolutionsPerMinute(double revolutionsperminute) - { - double value = (double) revolutionsperminute; - return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalSpeed FromRevolutionsPerSecond(double revolutionspersecond) - { - double value = (double) revolutionspersecond; - return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalSpeed unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) - { - return new RotationalSpeed((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalSpeed Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalSpeed Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out RotationalSpeed result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalSpeedUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RotationalSpeedUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalSpeed objRotationalSpeed)) throw new ArgumentException("Expected type RotationalSpeed.", nameof(obj)); - - return CompareTo(objRotationalSpeed); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(RotationalSpeed other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalSpeed objRotationalSpeed)) - return false; - - return Equals(objRotationalSpeed); - } - - public bool Equals(RotationalSpeed other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalSpeed within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalSpeed other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalSpeed. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RotationalSpeedUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalSpeedUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . - /// - /// A RotationalSpeed with the specified unit. - public RotationalSpeed ToUnit(RotationalSpeedUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalSpeed(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (_value) * 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (_value) * 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (Math.PI / (180 * 60)) * _value; - case RotationalSpeedUnit.DegreePerSecond: return (Math.PI / 180) * _value; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((Math.PI / 180) * _value) * 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (_value) * 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((Math.PI / 180) * _value) * 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (_value) * 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((Math.PI / 180) * _value) * 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (_value) * 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return _value; - case RotationalSpeedUnit.RevolutionPerMinute: return (_value * 6.2831853072) / 60; - case RotationalSpeedUnit.RevolutionPerSecond: return _value * 6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalSpeedUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalSpeedUnit.CentiradianPerSecond: return (baseUnitValue) / 1e-2d; - case RotationalSpeedUnit.DeciradianPerSecond: return (baseUnitValue) / 1e-1d; - case RotationalSpeedUnit.DegreePerMinute: return (180 * 60 / Math.PI) * baseUnitValue; - case RotationalSpeedUnit.DegreePerSecond: return (180 / Math.PI) * baseUnitValue; - case RotationalSpeedUnit.MicrodegreePerSecond: return ((180 / Math.PI) * baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MicroradianPerSecond: return (baseUnitValue) / 1e-6d; - case RotationalSpeedUnit.MillidegreePerSecond: return ((180 / Math.PI) * baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.MilliradianPerSecond: return (baseUnitValue) / 1e-3d; - case RotationalSpeedUnit.NanodegreePerSecond: return ((180 / Math.PI) * baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.NanoradianPerSecond: return (baseUnitValue) / 1e-9d; - case RotationalSpeedUnit.RadianPerSecond: return baseUnitValue; - case RotationalSpeedUnit.RevolutionPerMinute: return (baseUnitValue / 6.2831853072) * 60; - case RotationalSpeedUnit.RevolutionPerSecond: return baseUnitValue / 6.2831853072; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.g.cs deleted file mode 100644 index 6656027c06..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ /dev/null @@ -1,1201 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalStiffness : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalStiffnessUnit? _unit; - - static RotationalStiffness() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = RotationalStiffnessUnit.NewtonMeterPerRadian; - MaxValue = new RotationalStiffness(double.MaxValue, BaseUnit); - MinValue = new RotationalStiffness(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalStiffness; - Units = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); - Zero = new RotationalStiffness(0, BaseUnit); - Info = new QuantityInfo(QuantityType.RotationalStiffness, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerRadian. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public RotationalStiffness() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private RotationalStiffness(double value, RotationalStiffnessUnit unit) - { - if (unit == RotationalStiffnessUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. - /// - public static RotationalStiffnessUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of RotationalStiffness - /// - public static RotationalStiffness MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalStiffness - /// - public static RotationalStiffness MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the RotationalStiffness quantity. - /// - public static RotationalStiffnessUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. - /// - public static RotationalStiffness Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => RotationalStiffness.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonMetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double CentinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonMetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double DecanewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonMetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double DecinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundForceFeetPerDegrees => As(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonMetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double MicronewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonMetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double MillinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonMetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double NanonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMetersPerDegree => As(RotationalStiffnessUnit.NewtonMeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NewtonMillimeterPerDegree); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NewtonMillimeterPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceFeetPerRadian => As(RotationalStiffnessUnit.PoundForceFeetPerRadian); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceFeetPerDegrees => As(RotationalStiffnessUnit.PoundForceFootPerDegrees); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RotationalStiffnessUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RotationalStiffnessUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromCentinewtonMetersPerDegree(double centinewtonmetersperdegree) - { - double value = (double) centinewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromCentinewtonMillimetersPerDegree(double centinewtonmillimetersperdegree) - { - double value = (double) centinewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromCentinewtonMillimetersPerRadian(double centinewtonmillimetersperradian) - { - double value = (double) centinewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromDecanewtonMetersPerDegree(double decanewtonmetersperdegree) - { - double value = (double) decanewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromDecanewtonMillimetersPerDegree(double decanewtonmillimetersperdegree) - { - double value = (double) decanewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromDecanewtonMillimetersPerRadian(double decanewtonmillimetersperradian) - { - double value = (double) decanewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromDecinewtonMetersPerDegree(double decinewtonmetersperdegree) - { - double value = (double) decinewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromDecinewtonMillimetersPerDegree(double decinewtonmillimetersperdegree) - { - double value = (double) decinewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromDecinewtonMillimetersPerRadian(double decinewtonmillimetersperradian) - { - double value = (double) decinewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilonewtonMetersPerDegree(double kilonewtonmetersperdegree) - { - double value = (double) kilonewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilonewtonMetersPerRadian(double kilonewtonmetersperradian) - { - double value = (double) kilonewtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilonewtonMillimetersPerDegree(double kilonewtonmillimetersperdegree) - { - double value = (double) kilonewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilonewtonMillimetersPerRadian(double kilonewtonmillimetersperradian) - { - double value = (double) kilonewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromKilopoundForceFeetPerDegrees(double kilopoundforcefeetperdegrees) - { - double value = (double) kilopoundforcefeetperdegrees; - return new RotationalStiffness(value, RotationalStiffnessUnit.KilopoundForceFootPerDegrees); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMeganewtonMetersPerDegree(double meganewtonmetersperdegree) - { - double value = (double) meganewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMeganewtonMetersPerRadian(double meganewtonmetersperradian) - { - double value = (double) meganewtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMeganewtonMillimetersPerDegree(double meganewtonmillimetersperdegree) - { - double value = (double) meganewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMeganewtonMillimetersPerRadian(double meganewtonmillimetersperradian) - { - double value = (double) meganewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMicronewtonMetersPerDegree(double micronewtonmetersperdegree) - { - double value = (double) micronewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMicronewtonMillimetersPerDegree(double micronewtonmillimetersperdegree) - { - double value = (double) micronewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMicronewtonMillimetersPerRadian(double micronewtonmillimetersperradian) - { - double value = (double) micronewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMillinewtonMetersPerDegree(double millinewtonmetersperdegree) - { - double value = (double) millinewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMillinewtonMillimetersPerDegree(double millinewtonmillimetersperdegree) - { - double value = (double) millinewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromMillinewtonMillimetersPerRadian(double millinewtonmillimetersperradian) - { - double value = (double) millinewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNanonewtonMetersPerDegree(double nanonewtonmetersperdegree) - { - double value = (double) nanonewtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNanonewtonMillimetersPerDegree(double nanonewtonmillimetersperdegree) - { - double value = (double) nanonewtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNanonewtonMillimetersPerRadian(double nanonewtonmillimetersperradian) - { - double value = (double) nanonewtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNewtonMetersPerDegree(double newtonmetersperdegree) - { - double value = (double) newtonmetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNewtonMetersPerRadian(double newtonmetersperradian) - { - double value = (double) newtonmetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNewtonMillimetersPerDegree(double newtonmillimetersperdegree) - { - double value = (double) newtonmillimetersperdegree; - return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerDegree); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromNewtonMillimetersPerRadian(double newtonmillimetersperradian) - { - double value = (double) newtonmillimetersperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromPoundForceFeetPerRadian(double poundforcefeetperradian) - { - double value = (double) poundforcefeetperradian; - return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFeetPerRadian); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffness FromPoundForceFeetPerDegrees(double poundforcefeetperdegrees) - { - double value = (double) poundforcefeetperdegrees; - return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFootPerDegrees); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalStiffness unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalStiffness From(double value, RotationalStiffnessUnit fromUnit) - { - return new RotationalStiffness((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalStiffness Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalStiffness Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalStiffness result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out RotationalStiffness result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalStiffnessUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RotationalStiffnessUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalStiffness objRotationalStiffness)) throw new ArgumentException("Expected type RotationalStiffness.", nameof(obj)); - - return CompareTo(objRotationalStiffness); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(RotationalStiffness other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalStiffness objRotationalStiffness)) - return false; - - return Equals(objRotationalStiffness); - } - - public bool Equals(RotationalStiffness other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalStiffness within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalStiffness other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffness. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RotationalStiffnessUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . - /// - /// A RotationalStiffness with the specified unit. - public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalStiffness(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessUnit.CentinewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerRadian: return (_value * 0.001) * 1e-2d; - case RotationalStiffnessUnit.DecanewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerRadian: return (_value * 0.001) * 1e1d; - case RotationalStiffnessUnit.DecinewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerRadian: return (_value * 0.001) * 1e-1d; - case RotationalStiffnessUnit.KilonewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e3d; - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (_value) * 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerRadian: return (_value * 0.001) * 1e3d; - case RotationalStiffnessUnit.KilopoundForceFootPerDegrees: return _value * 77682.6; - case RotationalStiffnessUnit.MeganewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e6d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (_value) * 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerRadian: return (_value * 0.001) * 1e6d; - case RotationalStiffnessUnit.MicronewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerRadian: return (_value * 0.001) * 1e-6d; - case RotationalStiffnessUnit.MillinewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerRadian: return (_value * 0.001) * 1e-3d; - case RotationalStiffnessUnit.NanonewtonMeterPerDegree: return (_value * (180 / Math.PI)) * 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerDegree: return (_value * 180 / Math.PI * 0.001) * 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerRadian: return (_value * 0.001) * 1e-9d; - case RotationalStiffnessUnit.NewtonMeterPerDegree: return _value * (180 / Math.PI); - case RotationalStiffnessUnit.NewtonMeterPerRadian: return _value; - case RotationalStiffnessUnit.NewtonMillimeterPerDegree: return _value * 180 / Math.PI * 0.001; - case RotationalStiffnessUnit.NewtonMillimeterPerRadian: return _value * 0.001; - case RotationalStiffnessUnit.PoundForceFeetPerRadian: return _value * 1.3558179483314; - case RotationalStiffnessUnit.PoundForceFootPerDegrees: return _value * 77.6826; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalStiffnessUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalStiffnessUnit.CentinewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e-2d; - case RotationalStiffnessUnit.CentinewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e-2d; - case RotationalStiffnessUnit.DecanewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e1d; - case RotationalStiffnessUnit.DecanewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e1d; - case RotationalStiffnessUnit.DecinewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e-1d; - case RotationalStiffnessUnit.DecinewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e-1d; - case RotationalStiffnessUnit.KilonewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e3d; - case RotationalStiffnessUnit.KilonewtonMeterPerRadian: return (baseUnitValue) / 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e3d; - case RotationalStiffnessUnit.KilonewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e3d; - case RotationalStiffnessUnit.KilopoundForceFootPerDegrees: return baseUnitValue / 77682.6; - case RotationalStiffnessUnit.MeganewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e6d; - case RotationalStiffnessUnit.MeganewtonMeterPerRadian: return (baseUnitValue) / 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e6d; - case RotationalStiffnessUnit.MeganewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e6d; - case RotationalStiffnessUnit.MicronewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e-6d; - case RotationalStiffnessUnit.MicronewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e-6d; - case RotationalStiffnessUnit.MillinewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e-3d; - case RotationalStiffnessUnit.MillinewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e-3d; - case RotationalStiffnessUnit.NanonewtonMeterPerDegree: return (baseUnitValue / (180 / Math.PI)) / 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerDegree: return (baseUnitValue / 180 * Math.PI * 1000) / 1e-9d; - case RotationalStiffnessUnit.NanonewtonMillimeterPerRadian: return (baseUnitValue * 1000) / 1e-9d; - case RotationalStiffnessUnit.NewtonMeterPerDegree: return baseUnitValue / (180 / Math.PI); - case RotationalStiffnessUnit.NewtonMeterPerRadian: return baseUnitValue; - case RotationalStiffnessUnit.NewtonMillimeterPerDegree: return baseUnitValue / 180 * Math.PI * 1000; - case RotationalStiffnessUnit.NewtonMillimeterPerRadian: return baseUnitValue * 1000; - case RotationalStiffnessUnit.PoundForceFeetPerRadian: return baseUnitValue / 1.3558179483314; - case RotationalStiffnessUnit.PoundForceFootPerDegrees: return baseUnitValue / 77.6826; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs deleted file mode 100644 index 1a9dee9a8f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ /dev/null @@ -1,669 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class RotationalStiffnessPerLength : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly RotationalStiffnessPerLengthUnit? _unit; - - static RotationalStiffnessPerLength() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - BaseUnit = RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; - MaxValue = new RotationalStiffnessPerLength(double.MaxValue, BaseUnit); - MinValue = new RotationalStiffnessPerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalStiffnessPerLength; - Units = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); - Zero = new RotationalStiffnessPerLength(0, BaseUnit); - Info = new QuantityInfo(QuantityType.RotationalStiffnessPerLength, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public RotationalStiffnessPerLength() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private RotationalStiffnessPerLength(double value, RotationalStiffnessPerLengthUnit unit) - { - if (unit == RotationalStiffnessPerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. - /// - public static RotationalStiffnessPerLengthUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of RotationalStiffnessPerLength - /// - public static RotationalStiffnessPerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalStiffnessPerLength - /// - public static RotationalStiffnessPerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the RotationalStiffnessPerLength quantity. - /// - public static RotationalStiffnessPerLengthUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. - /// - public static RotationalStiffnessPerLength Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => RotationalStiffnessPerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(double kilonewtonmetersperradianpermeter) - { - double value = (double) kilonewtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFeet(double kilopoundforcefeetperdegreesperfeet) - { - double value = (double) kilopoundforcefeetperdegreesperfeet; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(double meganewtonmetersperradianpermeter) - { - double value = (double) meganewtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(double newtonmetersperradianpermeter) - { - double value = (double) newtonmetersperradianpermeter; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(double poundforcefeetperdegreesperfeet) - { - double value = (double) poundforcefeetperdegreesperfeet; - return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// RotationalStiffnessPerLength unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static RotationalStiffnessPerLength From(double value, RotationalStiffnessPerLengthUnit fromUnit) - { - return new RotationalStiffnessPerLength((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static RotationalStiffnessPerLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalStiffnessPerLength Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out RotationalStiffnessPerLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out RotationalStiffnessPerLength result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static RotationalStiffnessPerLengthUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static RotationalStiffnessPerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out RotationalStiffnessPerLengthUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalStiffnessPerLength objRotationalStiffnessPerLength)) throw new ArgumentException("Expected type RotationalStiffnessPerLength.", nameof(obj)); - - return CompareTo(objRotationalStiffnessPerLength); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(RotationalStiffnessPerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalStiffnessPerLength objRotationalStiffnessPerLength)) - return false; - - return Equals(objRotationalStiffnessPerLength); - } - - public bool Equals(RotationalStiffnessPerLength other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another RotationalStiffnessPerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(RotationalStiffnessPerLength other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffnessPerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((RotationalStiffnessPerLengthUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessPerLengthUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . - /// - /// A RotationalStiffnessPerLength with the specified unit. - public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new RotationalStiffnessPerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (_value) * 1e3d; - case RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot: return _value * 254864.324570; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (_value) * 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return _value; - case RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot: return _value * 254.864324570; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(RotationalStiffnessPerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e3d; - case RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot: return baseUnitValue / 254864.324570; - case RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter: return (baseUnitValue) / 1e6d; - case RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter: return baseUnitValue; - case RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot: return baseUnitValue / 254.864324570; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Scalar.g.cs deleted file mode 100644 index e777cfc9de..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Scalar.g.cs +++ /dev/null @@ -1,593 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A way of representing a number of items. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Scalar : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ScalarUnit? _unit; - - static Scalar() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = ScalarUnit.Amount; - MaxValue = new Scalar(double.MaxValue, BaseUnit); - MinValue = new Scalar(double.MinValue, BaseUnit); - QuantityType = QuantityType.Scalar; - Units = Enum.GetValues(typeof(ScalarUnit)).Cast().Except(new ScalarUnit[]{ ScalarUnit.Undefined }).ToArray(); - Zero = new Scalar(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Scalar, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Amount. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Scalar() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Scalar(double value, ScalarUnit unit) - { - if (unit == ScalarUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Scalar, which is Amount. All conversions go via this value. - /// - public static ScalarUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Scalar - /// - public static Scalar MaxValue { get; } - - /// - /// Represents the smallest possible value of Scalar - /// - public static Scalar MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Scalar quantity. - /// - public static ScalarUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Amount. - /// - public static Scalar Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ScalarUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Scalar.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Scalar.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Amount => As(ScalarUnit.Amount); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(ScalarUnit.Amount, new CultureInfo("en-US"), false, true, new string[]{""}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ScalarUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ScalarUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Scalar FromAmount(double amount) - { - double value = (double) amount; - return new Scalar(value, ScalarUnit.Amount); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Scalar unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Scalar From(double value, ScalarUnit fromUnit) - { - return new Scalar((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Scalar Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Scalar Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Scalar result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Scalar result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ScalarUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ScalarUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ScalarUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ScalarUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Scalar objScalar)) throw new ArgumentException("Expected type Scalar.", nameof(obj)); - - return CompareTo(objScalar); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Scalar other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Scalar objScalar)) - return false; - - return Equals(objScalar); - } - - public bool Equals(Scalar other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Scalar within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Scalar. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ScalarUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ScalarUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Scalar to another Scalar with the unit representation . - /// - /// A Scalar with the specified unit. - public Scalar ToUnit(ScalarUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Scalar(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ScalarUnit.Amount: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ScalarUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ScalarUnit.Amount: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.g.cs deleted file mode 100644 index f71334b801..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SolidAngle.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point. - /// - /// - /// https://en.wikipedia.org/wiki/Solid_angle - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SolidAngle : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SolidAngleUnit? _unit; - - static SolidAngle() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = SolidAngleUnit.Steradian; - MaxValue = new SolidAngle(double.MaxValue, BaseUnit); - MinValue = new SolidAngle(double.MinValue, BaseUnit); - QuantityType = QuantityType.SolidAngle; - Units = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); - Zero = new SolidAngle(0, BaseUnit); - Info = new QuantityInfo(QuantityType.SolidAngle, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Steradian. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public SolidAngle() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private SolidAngle(double value, SolidAngleUnit unit) - { - if (unit == SolidAngleUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. - /// - public static SolidAngleUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of SolidAngle - /// - public static SolidAngle MaxValue { get; } - - /// - /// Represents the smallest possible value of SolidAngle - /// - public static SolidAngle MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the SolidAngle quantity. - /// - public static SolidAngleUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. - /// - public static SolidAngle Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => SolidAngle.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SolidAngle.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Steradians => As(SolidAngleUnit.Steradian); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(SolidAngleUnit.Steradian, new CultureInfo("en-US"), false, true, new string[]{"sr"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SolidAngleUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SolidAngle FromSteradians(double steradians) - { - double value = (double) steradians; - return new SolidAngle(value, SolidAngleUnit.Steradian); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SolidAngle unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SolidAngle From(double value, SolidAngleUnit fromUnit) - { - return new SolidAngle((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SolidAngle Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SolidAngle Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SolidAngle result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out SolidAngle result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SolidAngleUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SolidAngleUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SolidAngleUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SolidAngle objSolidAngle)) throw new ArgumentException("Expected type SolidAngle.", nameof(obj)); - - return CompareTo(objSolidAngle); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(SolidAngle other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is SolidAngle objSolidAngle)) - return false; - - return Equals(objSolidAngle); - } - - public bool Equals(SolidAngle other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SolidAngle within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SolidAngle other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SolidAngle. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SolidAngleUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SolidAngleUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SolidAngle to another SolidAngle with the unit representation . - /// - /// A SolidAngle with the specified unit. - public SolidAngle ToUnit(SolidAngleUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SolidAngle(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SolidAngleUnit.Steradian: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SolidAngleUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SolidAngleUnit.Steradian: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.g.cs deleted file mode 100644 index 7fcff03632..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ /dev/null @@ -1,1128 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The SpecificEnergy - /// - /// - /// https://en.wikipedia.org/wiki/Specific_energy - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificEnergy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificEnergyUnit? _unit; - - static SpecificEnergy() - { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); - BaseUnit = SpecificEnergyUnit.JoulePerKilogram; - MaxValue = new SpecificEnergy(double.MaxValue, BaseUnit); - MinValue = new SpecificEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificEnergy; - Units = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); - Zero = new SpecificEnergy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.SpecificEnergy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerKilogram. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public SpecificEnergy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private SpecificEnergy(double value, SpecificEnergyUnit unit) - { - if (unit == SpecificEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. - /// - public static SpecificEnergyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of SpecificEnergy - /// - public static SpecificEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificEnergy - /// - public static SpecificEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the SpecificEnergy quantity. - /// - public static SpecificEnergyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. - /// - public static SpecificEnergy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => SpecificEnergy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BtuPerPound => As(SpecificEnergyUnit.BtuPerPound); - - /// - /// Gets a value of this quantity converted into - /// - public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattDaysPerKilogram => As(SpecificEnergyUnit.GigawattDayPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattDaysPerShortTon => As(SpecificEnergyUnit.GigawattDayPerShortTon); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattDaysPerTonne => As(SpecificEnergyUnit.GigawattDayPerTonne); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattHoursPerKilogram => As(SpecificEnergyUnit.GigawattHourPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double GigawattHoursPerPound => As(SpecificEnergyUnit.GigawattHourPerPound); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattDaysPerKilogram => As(SpecificEnergyUnit.KilowattDayPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattDaysPerShortTon => As(SpecificEnergyUnit.KilowattDayPerShortTon); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattDaysPerTonne => As(SpecificEnergyUnit.KilowattDayPerTonne); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double KilowattHoursPerPound => As(SpecificEnergyUnit.KilowattHourPerPound); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattDaysPerKilogram => As(SpecificEnergyUnit.MegawattDayPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattDaysPerShortTon => As(SpecificEnergyUnit.MegawattDayPerShortTon); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattDaysPerTonne => As(SpecificEnergyUnit.MegawattDayPerTonne); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double MegawattHoursPerPound => As(SpecificEnergyUnit.MegawattHourPerPound); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattDaysPerKilogram => As(SpecificEnergyUnit.TerawattDayPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattDaysPerShortTon => As(SpecificEnergyUnit.TerawattDayPerShortTon); - - /// - /// Gets a value of this quantity converted into - /// - public double TerawattDaysPerTonne => As(SpecificEnergyUnit.TerawattDayPerTonne); - - /// - /// Gets a value of this quantity converted into - /// - public double WattDaysPerKilogram => As(SpecificEnergyUnit.WattDayPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double WattDaysPerShortTon => As(SpecificEnergyUnit.WattDayPerShortTon); - - /// - /// Gets a value of this quantity converted into - /// - public double WattDaysPerTonne => As(SpecificEnergyUnit.WattDayPerTonne); - - /// - /// Gets a value of this quantity converted into - /// - public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double WattHoursPerPound => As(SpecificEnergyUnit.WattHourPerPound); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SpecificEnergyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromBtuPerPound(double btuperpound) - { - double value = (double) btuperpound; - return new SpecificEnergy(value, SpecificEnergyUnit.BtuPerPound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) - { - double value = (double) caloriespergram; - return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromGigawattDaysPerKilogram(double gigawattdaysperkilogram) - { - double value = (double) gigawattdaysperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromGigawattDaysPerShortTon(double gigawattdayspershortton) - { - double value = (double) gigawattdayspershortton; - return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerShortTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromGigawattDaysPerTonne(double gigawattdayspertonne) - { - double value = (double) gigawattdayspertonne; - return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerTonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromGigawattHoursPerKilogram(double gigawatthoursperkilogram) - { - double value = (double) gigawatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromGigawattHoursPerPound(double gigawatthoursperpound) - { - double value = (double) gigawatthoursperpound; - return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerPound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) - { - double value = (double) joulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) - { - double value = (double) kilocaloriespergram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) - { - double value = (double) kilojoulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattDaysPerKilogram(double kilowattdaysperkilogram) - { - double value = (double) kilowattdaysperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattDaysPerShortTon(double kilowattdayspershortton) - { - double value = (double) kilowattdayspershortton; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerShortTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattDaysPerTonne(double kilowattdayspertonne) - { - double value = (double) kilowattdayspertonne; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerTonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) - { - double value = (double) kilowatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromKilowattHoursPerPound(double kilowatthoursperpound) - { - double value = (double) kilowatthoursperpound; - return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerPound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) - { - double value = (double) megajoulesperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattDaysPerKilogram(double megawattdaysperkilogram) - { - double value = (double) megawattdaysperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattDaysPerShortTon(double megawattdayspershortton) - { - double value = (double) megawattdayspershortton; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerShortTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattDaysPerTonne(double megawattdayspertonne) - { - double value = (double) megawattdayspertonne; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerTonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) - { - double value = (double) megawatthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromMegawattHoursPerPound(double megawatthoursperpound) - { - double value = (double) megawatthoursperpound; - return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerPound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromTerawattDaysPerKilogram(double terawattdaysperkilogram) - { - double value = (double) terawattdaysperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromTerawattDaysPerShortTon(double terawattdayspershortton) - { - double value = (double) terawattdayspershortton; - return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerShortTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromTerawattDaysPerTonne(double terawattdayspertonne) - { - double value = (double) terawattdayspertonne; - return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerTonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattDaysPerKilogram(double wattdaysperkilogram) - { - double value = (double) wattdaysperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattDaysPerShortTon(double wattdayspershortton) - { - double value = (double) wattdayspershortton; - return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerShortTon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattDaysPerTonne(double wattdayspertonne) - { - double value = (double) wattdayspertonne; - return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerTonne); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) - { - double value = (double) watthoursperkilogram; - return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEnergy FromWattHoursPerPound(double watthoursperpound) - { - double value = (double) watthoursperpound; - return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerPound); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificEnergy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) - { - return new SpecificEnergy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificEnergy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificEnergy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out SpecificEnergy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEnergyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SpecificEnergyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificEnergy objSpecificEnergy)) throw new ArgumentException("Expected type SpecificEnergy.", nameof(obj)); - - return CompareTo(objSpecificEnergy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(SpecificEnergy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificEnergy objSpecificEnergy)) - return false; - - return Equals(objSpecificEnergy); - } - - public bool Equals(SpecificEnergy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SpecificEnergyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEnergyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation . - /// - /// A SpecificEnergy with the specified unit. - public SpecificEnergy ToUnit(SpecificEnergyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificEnergy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificEnergyUnit.BtuPerPound: return _value * 2326.000075362; - case SpecificEnergyUnit.CaloriePerGram: return _value * 4.184e3; - case SpecificEnergyUnit.GigawattDayPerKilogram: return (_value * (24 * 3.6e3)) * 1e9d; - case SpecificEnergyUnit.GigawattDayPerShortTon: return (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e9d; - case SpecificEnergyUnit.GigawattDayPerTonne: return (_value * ((24 * 3.6e3) / 1e3)) * 1e9d; - case SpecificEnergyUnit.GigawattHourPerKilogram: return (_value * 3.6e3) * 1e9d; - case SpecificEnergyUnit.GigawattHourPerPound: return (_value * 7.93664e3) * 1e9d; - case SpecificEnergyUnit.JoulePerKilogram: return _value; - case SpecificEnergyUnit.KilocaloriePerGram: return (_value * 4.184e3) * 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; - case SpecificEnergyUnit.KilowattDayPerKilogram: return (_value * (24 * 3.6e3)) * 1e3d; - case SpecificEnergyUnit.KilowattDayPerShortTon: return (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e3d; - case SpecificEnergyUnit.KilowattDayPerTonne: return (_value * ((24 * 3.6e3) / 1e3)) * 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value * 3.6e3) * 1e3d; - case SpecificEnergyUnit.KilowattHourPerPound: return (_value * 7.93664e3) * 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; - case SpecificEnergyUnit.MegawattDayPerKilogram: return (_value * (24 * 3.6e3)) * 1e6d; - case SpecificEnergyUnit.MegawattDayPerShortTon: return (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e6d; - case SpecificEnergyUnit.MegawattDayPerTonne: return (_value * ((24 * 3.6e3) / 1e3)) * 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value * 3.6e3) * 1e6d; - case SpecificEnergyUnit.MegawattHourPerPound: return (_value * 7.93664e3) * 1e6d; - case SpecificEnergyUnit.TerawattDayPerKilogram: return (_value * (24 * 3.6e3)) * 1e12d; - case SpecificEnergyUnit.TerawattDayPerShortTon: return (_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e12d; - case SpecificEnergyUnit.TerawattDayPerTonne: return (_value * ((24 * 3.6e3) / 1e3)) * 1e12d; - case SpecificEnergyUnit.WattDayPerKilogram: return _value * (24 * 3.6e3); - case SpecificEnergyUnit.WattDayPerShortTon: return _value * ((24 * 3.6e3) / 9.0718474e2); - case SpecificEnergyUnit.WattDayPerTonne: return _value * ((24 * 3.6e3) / 1e3); - case SpecificEnergyUnit.WattHourPerKilogram: return _value * 3.6e3; - case SpecificEnergyUnit.WattHourPerPound: return _value * 7.93664e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificEnergyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificEnergyUnit.BtuPerPound: return baseUnitValue / 2326.000075362; - case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue / 4.184e3; - case SpecificEnergyUnit.GigawattDayPerKilogram: return (baseUnitValue / (24 * 3.6e3)) / 1e9d; - case SpecificEnergyUnit.GigawattDayPerShortTon: return (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e9d; - case SpecificEnergyUnit.GigawattDayPerTonne: return (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e9d; - case SpecificEnergyUnit.GigawattHourPerKilogram: return (baseUnitValue / 3.6e3) / 1e9d; - case SpecificEnergyUnit.GigawattHourPerPound: return (baseUnitValue / 7.93664e3) / 1e9d; - case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; - case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue / 4.184e3) / 1e3d; - case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; - case SpecificEnergyUnit.KilowattDayPerKilogram: return (baseUnitValue / (24 * 3.6e3)) / 1e3d; - case SpecificEnergyUnit.KilowattDayPerShortTon: return (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e3d; - case SpecificEnergyUnit.KilowattDayPerTonne: return (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e3d; - case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue / 3.6e3) / 1e3d; - case SpecificEnergyUnit.KilowattHourPerPound: return (baseUnitValue / 7.93664e3) / 1e3d; - case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; - case SpecificEnergyUnit.MegawattDayPerKilogram: return (baseUnitValue / (24 * 3.6e3)) / 1e6d; - case SpecificEnergyUnit.MegawattDayPerShortTon: return (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e6d; - case SpecificEnergyUnit.MegawattDayPerTonne: return (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e6d; - case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue / 3.6e3) / 1e6d; - case SpecificEnergyUnit.MegawattHourPerPound: return (baseUnitValue / 7.93664e3) / 1e6d; - case SpecificEnergyUnit.TerawattDayPerKilogram: return (baseUnitValue / (24 * 3.6e3)) / 1e12d; - case SpecificEnergyUnit.TerawattDayPerShortTon: return (baseUnitValue / ((24 * 3.6e3) / 9.0718474e2)) / 1e12d; - case SpecificEnergyUnit.TerawattDayPerTonne: return (baseUnitValue / ((24 * 3.6e3) / 1e3)) / 1e12d; - case SpecificEnergyUnit.WattDayPerKilogram: return baseUnitValue / (24 * 3.6e3); - case SpecificEnergyUnit.WattDayPerShortTon: return baseUnitValue / ((24 * 3.6e3) / 9.0718474e2); - case SpecificEnergyUnit.WattDayPerTonne: return baseUnitValue / ((24 * 3.6e3) / 1e3); - case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue / 3.6e3; - case SpecificEnergyUnit.WattHourPerPound: return baseUnitValue / 7.93664e3; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.g.cs deleted file mode 100644 index 59af636dda..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ /dev/null @@ -1,745 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificEntropy : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificEntropyUnit? _unit; - - static SpecificEntropy() - { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); - BaseUnit = SpecificEntropyUnit.JoulePerKilogramKelvin; - MaxValue = new SpecificEntropy(double.MaxValue, BaseUnit); - MinValue = new SpecificEntropy(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificEntropy; - Units = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); - Zero = new SpecificEntropy(0, BaseUnit); - Info = new QuantityInfo(QuantityType.SpecificEntropy, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerKilogramKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public SpecificEntropy() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private SpecificEntropy(double value, SpecificEntropyUnit unit) - { - if (unit == SpecificEntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. - /// - public static SpecificEntropyUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of SpecificEntropy - /// - public static SpecificEntropy MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificEntropy - /// - public static SpecificEntropy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the SpecificEntropy quantity. - /// - public static SpecificEntropyUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. - /// - public static SpecificEntropy Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => SpecificEntropy.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerPoundFahrenheit => As(SpecificEntropyUnit.BtuPerPoundFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SpecificEntropyUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromBtusPerPoundFahrenheit(double btusperpoundfahrenheit) - { - double value = (double) btusperpoundfahrenheit; - return new SpecificEntropy(value, SpecificEntropyUnit.BtuPerPoundFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromCaloriesPerGramKelvin(double caloriespergramkelvin) - { - double value = (double) caloriespergramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double joulesperkilogramdegreecelsius) - { - double value = (double) joulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromJoulesPerKilogramKelvin(double joulesperkilogramkelvin) - { - double value = (double) joulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilocaloriesPerGramKelvin(double kilocaloriespergramkelvin) - { - double value = (double) kilocaloriespergramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double kilojoulesperkilogramdegreecelsius) - { - double value = (double) kilojoulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double kilojoulesperkilogramkelvin) - { - double value = (double) kilojoulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double megajoulesperkilogramdegreecelsius) - { - double value = (double) megajoulesperkilogramdegreecelsius; - return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double megajoulesperkilogramkelvin) - { - double value = (double) megajoulesperkilogramkelvin; - return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificEntropy unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) - { - return new SpecificEntropy((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificEntropy Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificEntropy Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out SpecificEntropy result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificEntropyUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SpecificEntropyUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificEntropy objSpecificEntropy)) throw new ArgumentException("Expected type SpecificEntropy.", nameof(obj)); - - return CompareTo(objSpecificEntropy); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(SpecificEntropy other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificEntropy objSpecificEntropy)) - return false; - - return Equals(objSpecificEntropy); - } - - public bool Equals(SpecificEntropy other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificEntropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificEntropy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEntropy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SpecificEntropyUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEntropyUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation . - /// - /// A SpecificEntropy with the specified unit. - public SpecificEntropy ToUnit(SpecificEntropyUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificEntropy(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificEntropyUnit.BtuPerPoundFahrenheit: return _value * 4.1868e3; - case SpecificEntropyUnit.CaloriePerGramKelvin: return _value * 4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return _value; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return _value; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (_value * 4.184e3) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (_value) * 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (_value) * 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (_value) * 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificEntropyUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificEntropyUnit.BtuPerPoundFahrenheit: return baseUnitValue / 4.1868e3; - case SpecificEntropyUnit.CaloriePerGramKelvin: return baseUnitValue / 4.184e3; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return baseUnitValue; - case SpecificEntropyUnit.JoulePerKilogramKelvin: return baseUnitValue; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (baseUnitValue / 4.184e3) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (baseUnitValue) / 1e3d; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e6d; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs deleted file mode 100644 index 08c3807cb7..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ /dev/null @@ -1,653 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// SFC is the fuel efficiency of an engine design with respect to thrust output - /// - /// - /// https://en.wikipedia.org/wiki/Thrust-specific_fuel_consumption - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificFuelConsumption : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificFuelConsumptionUnit? _unit; - - static SpecificFuelConsumption() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond; - MaxValue = new SpecificFuelConsumption(double.MaxValue, BaseUnit); - MinValue = new SpecificFuelConsumption(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificFuelConsumption; - Units = Enum.GetValues(typeof(SpecificFuelConsumptionUnit)).Cast().Except(new SpecificFuelConsumptionUnit[]{ SpecificFuelConsumptionUnit.Undefined }).ToArray(); - Zero = new SpecificFuelConsumption(0, BaseUnit); - Info = new QuantityInfo(QuantityType.SpecificFuelConsumption, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit GramPerKiloNewtonSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public SpecificFuelConsumption() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private SpecificFuelConsumption(double value, SpecificFuelConsumptionUnit unit) - { - if (unit == SpecificFuelConsumptionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of SpecificFuelConsumption, which is GramPerKiloNewtonSecond. All conversions go via this value. - /// - public static SpecificFuelConsumptionUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of SpecificFuelConsumption - /// - public static SpecificFuelConsumption MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificFuelConsumption - /// - public static SpecificFuelConsumption MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the SpecificFuelConsumption quantity. - /// - public static SpecificFuelConsumptionUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit GramPerKiloNewtonSecond. - /// - public static SpecificFuelConsumption Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => SpecificFuelConsumption.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificFuelConsumption.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerKilogramForceHour => As(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsMassPerPoundForceHour => As(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); - - #endregion - - #region Static Methods - - 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)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SpecificFuelConsumptionUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SpecificFuelConsumptionUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificFuelConsumption FromGramsPerKiloNewtonSecond(double gramsperkilonewtonsecond) - { - double value = (double) gramsperkilonewtonsecond; - return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(double kilogramsperkilogramforcehour) - { - double value = (double) kilogramsperkilogramforcehour; - return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificFuelConsumption FromKilogramsPerKiloNewtonSecond(double kilogramsperkilonewtonsecond) - { - double value = (double) kilogramsperkilonewtonsecond; - return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(double poundsmassperpoundforcehour) - { - double value = (double) poundsmassperpoundforcehour; - return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificFuelConsumption unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificFuelConsumption From(double value, SpecificFuelConsumptionUnit fromUnit) - { - return new SpecificFuelConsumption((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificFuelConsumption Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificFuelConsumption Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificFuelConsumption result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out SpecificFuelConsumption result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificFuelConsumptionUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SpecificFuelConsumptionUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SpecificFuelConsumptionUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificFuelConsumption objSpecificFuelConsumption)) throw new ArgumentException("Expected type SpecificFuelConsumption.", nameof(obj)); - - return CompareTo(objSpecificFuelConsumption); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(SpecificFuelConsumption other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificFuelConsumption objSpecificFuelConsumption)) - return false; - - return Equals(objSpecificFuelConsumption); - } - - public bool Equals(SpecificFuelConsumption other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificFuelConsumption within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificFuelConsumption. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SpecificFuelConsumptionUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificFuelConsumption to another SpecificFuelConsumption with the unit representation . - /// - /// A SpecificFuelConsumption with the specified unit. - public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificFuelConsumption(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond: return _value; - case SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour: return _value * 28.33; - case SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond: return (_value) * 1e3d; - case SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour: return _value * 28.33; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond: return baseUnitValue; - case SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour: return baseUnitValue / 28.33; - case SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond: return (baseUnitValue) / 1e3d; - case SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour: return baseUnitValue / 28.33; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.g.cs deleted file mode 100644 index 55cfb633ef..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificVolume.g.cs +++ /dev/null @@ -1,631 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificVolume : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificVolumeUnit? _unit; - - static SpecificVolume() - { - BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); - BaseUnit = SpecificVolumeUnit.CubicMeterPerKilogram; - MaxValue = new SpecificVolume(double.MaxValue, BaseUnit); - MinValue = new SpecificVolume(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificVolume; - Units = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); - Zero = new SpecificVolume(0, BaseUnit); - Info = new QuantityInfo(QuantityType.SpecificVolume, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CubicMeterPerKilogram. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public SpecificVolume() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private SpecificVolume(double value, SpecificVolumeUnit unit) - { - if (unit == SpecificVolumeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. - /// - public static SpecificVolumeUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of SpecificVolume - /// - public static SpecificVolume MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificVolume - /// - public static SpecificVolume MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the SpecificVolume quantity. - /// - public static SpecificVolumeUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. - /// - public static SpecificVolume Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => SpecificVolume.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); - - /// - /// Gets a value of this quantity converted into - /// - public double MillicubicMetersPerKilogram => As(SpecificVolumeUnit.MillicubicMeterPerKilogram); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SpecificVolumeUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromCubicFeetPerPound(double cubicfeetperpound) - { - double value = (double) cubicfeetperpound; - return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromCubicMetersPerKilogram(double cubicmetersperkilogram) - { - double value = (double) cubicmetersperkilogram; - return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificVolume FromMillicubicMetersPerKilogram(double millicubicmetersperkilogram) - { - double value = (double) millicubicmetersperkilogram; - return new SpecificVolume(value, SpecificVolumeUnit.MillicubicMeterPerKilogram); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificVolume unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) - { - return new SpecificVolume((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificVolume Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificVolume Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificVolume result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out SpecificVolume result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificVolumeUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SpecificVolumeUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificVolume objSpecificVolume)) throw new ArgumentException("Expected type SpecificVolume.", nameof(obj)); - - return CompareTo(objSpecificVolume); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(SpecificVolume other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificVolume objSpecificVolume)) - return false; - - return Equals(objSpecificVolume); - } - - public bool Equals(SpecificVolume other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificVolume within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificVolume other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificVolume. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SpecificVolumeUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificVolumeUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificVolume to another SpecificVolume with the unit representation . - /// - /// A SpecificVolume with the specified unit. - public SpecificVolume ToUnit(SpecificVolumeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificVolume(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return _value / 16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; - case SpecificVolumeUnit.MillicubicMeterPerKilogram: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificVolumeUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificVolumeUnit.CubicFootPerPound: return baseUnitValue * 16.01846353; - case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; - case SpecificVolumeUnit.MillicubicMeterPerKilogram: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.g.cs deleted file mode 100644 index 9295f7c400..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/SpecificWeight.g.cs +++ /dev/null @@ -1,900 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. - /// - /// - /// http://en.wikipedia.org/wiki/Specificweight - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class SpecificWeight : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpecificWeightUnit? _unit; - - static SpecificWeight() - { - BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); - BaseUnit = SpecificWeightUnit.NewtonPerCubicMeter; - MaxValue = new SpecificWeight(double.MaxValue, BaseUnit); - MinValue = new SpecificWeight(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificWeight; - Units = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); - Zero = new SpecificWeight(0, BaseUnit); - Info = new QuantityInfo(QuantityType.SpecificWeight, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonPerCubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public SpecificWeight() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private SpecificWeight(double value, SpecificWeightUnit unit) - { - if (unit == SpecificWeightUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. - /// - public static SpecificWeightUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of SpecificWeight - /// - public static SpecificWeight MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificWeight - /// - public static SpecificWeight MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the SpecificWeight quantity. - /// - public static SpecificWeightUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. - /// - public static SpecificWeight Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => SpecificWeight.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); - - #endregion - - #region Static Methods - - 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³"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SpecificWeightUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double kilogramsforcepercubiccentimeter) - { - double value = (double) kilogramsforcepercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicMeter(double kilogramsforcepercubicmeter) - { - double value = (double) kilogramsforcepercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double kilogramsforcepercubicmillimeter) - { - double value = (double) kilogramsforcepercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double kilonewtonspercubiccentimeter) - { - double value = (double) kilonewtonspercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicMeter(double kilonewtonspercubicmeter) - { - double value = (double) kilonewtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double kilonewtonspercubicmillimeter) - { - double value = (double) kilonewtonspercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilopoundsForcePerCubicFoot(double kilopoundsforcepercubicfoot) - { - double value = (double) kilopoundsforcepercubicfoot; - return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromKilopoundsForcePerCubicInch(double kilopoundsforcepercubicinch) - { - double value = (double) kilopoundsforcepercubicinch; - return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromMeganewtonsPerCubicMeter(double meganewtonspercubicmeter) - { - double value = (double) meganewtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicCentimeter(double newtonspercubiccentimeter) - { - double value = (double) newtonspercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicMeter(double newtonspercubicmeter) - { - double value = (double) newtonspercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromNewtonsPerCubicMillimeter(double newtonspercubicmillimeter) - { - double value = (double) newtonspercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromPoundsForcePerCubicFoot(double poundsforcepercubicfoot) - { - double value = (double) poundsforcepercubicfoot; - return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromPoundsForcePerCubicInch(double poundsforcepercubicinch) - { - double value = (double) poundsforcepercubicinch; - return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicCentimeter(double tonnesforcepercubiccentimeter) - { - double value = (double) tonnesforcepercubiccentimeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicMeter(double tonnesforcepercubicmeter) - { - double value = (double) tonnesforcepercubicmeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static SpecificWeight FromTonnesForcePerCubicMillimeter(double tonnesforcepercubicmillimeter) - { - double value = (double) tonnesforcepercubicmillimeter; - return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// SpecificWeight unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) - { - return new SpecificWeight((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static SpecificWeight Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificWeight Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out SpecificWeight result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out SpecificWeight result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpecificWeightUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SpecificWeightUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SpecificWeightUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificWeight objSpecificWeight)) throw new ArgumentException("Expected type SpecificWeight.", nameof(obj)); - - return CompareTo(objSpecificWeight); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(SpecificWeight other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificWeight objSpecificWeight)) - return false; - - return Equals(objSpecificWeight); - } - - public bool Equals(SpecificWeight other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another SpecificWeight within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(SpecificWeight other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificWeight. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SpecificWeightUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificWeightUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this SpecificWeight to another SpecificWeight with the unit representation . - /// - /// A SpecificWeight with the specified unit. - public SpecificWeight ToUnit(SpecificWeightUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new SpecificWeight(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return _value * 9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return _value * 9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return _value * 9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (_value * 1000000) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (_value) * 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (_value * 1000000000) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (_value * 1.570874638462462e2) * 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (_value * 2.714471375263134e5) * 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (_value) * 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return _value * 1000000; - case SpecificWeightUnit.NewtonPerCubicMeter: return _value; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return _value * 1000000000; - case SpecificWeightUnit.PoundForcePerCubicFoot: return _value * 1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return _value * 2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return _value * 9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return _value * 9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return _value * 9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpecificWeightUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return baseUnitValue / 9.80665e6; - case SpecificWeightUnit.KilogramForcePerCubicMeter: return baseUnitValue / 9.80665; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return baseUnitValue / 9.80665e9; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (baseUnitValue * 0.000001) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMeter: return (baseUnitValue) / 1e3d; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (baseUnitValue * 0.000000001) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (baseUnitValue / 1.570874638462462e2) / 1e3d; - case SpecificWeightUnit.KilopoundForcePerCubicInch: return (baseUnitValue / 2.714471375263134e5) / 1e3d; - case SpecificWeightUnit.MeganewtonPerCubicMeter: return (baseUnitValue) / 1e6d; - case SpecificWeightUnit.NewtonPerCubicCentimeter: return baseUnitValue * 0.000001; - case SpecificWeightUnit.NewtonPerCubicMeter: return baseUnitValue; - case SpecificWeightUnit.NewtonPerCubicMillimeter: return baseUnitValue * 0.000000001; - case SpecificWeightUnit.PoundForcePerCubicFoot: return baseUnitValue / 1.570874638462462e2; - case SpecificWeightUnit.PoundForcePerCubicInch: return baseUnitValue / 2.714471375263134e5; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: return baseUnitValue / 9.80665e9; - case SpecificWeightUnit.TonneForcePerCubicMeter: return baseUnitValue / 9.80665e3; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: return baseUnitValue / 9.80665e12; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.g.cs deleted file mode 100644 index fe0f84bdf1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Speed.g.cs +++ /dev/null @@ -1,1225 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Speed : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly SpeedUnit? _unit; - - static Speed() - { - BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); - BaseUnit = SpeedUnit.MeterPerSecond; - MaxValue = new Speed(double.MaxValue, BaseUnit); - MinValue = new Speed(double.MinValue, BaseUnit); - QuantityType = QuantityType.Speed; - Units = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); - Zero = new Speed(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Speed, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit MeterPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Speed() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Speed(double value, SpeedUnit unit) - { - if (unit == SpeedUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. - /// - public static SpeedUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Speed - /// - public static Speed MaxValue { get; } - - /// - /// Represents the smallest possible value of Speed - /// - public static Speed MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Speed quantity. - /// - public static SpeedUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. - /// - public static Speed Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Speed.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Speed.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetPerHour => As(SpeedUnit.FootPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetPerMinute => As(SpeedUnit.FootPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetPerSecond => As(SpeedUnit.FootPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesPerHour => As(SpeedUnit.InchPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesPerMinute => As(SpeedUnit.InchPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesPerSecond => As(SpeedUnit.InchPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double Knots => As(SpeedUnit.Knot); - - /// - /// Gets a value of this quantity converted into - /// - public double Mach => As(SpeedUnit.Mach); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersPerHour => As(SpeedUnit.MeterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MilesPerHour => As(SpeedUnit.MilePerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double YardsPerHour => As(SpeedUnit.YardPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double YardsPerMinute => As(SpeedUnit.YardPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double YardsPerSecond => As(SpeedUnit.YardPerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(SpeedUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerHour(double centimetersperhour) - { - double value = (double) centimetersperhour; - return new Speed(value, SpeedUnit.CentimeterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerMinutes(double centimetersperminutes) - { - double value = (double) centimetersperminutes; - return new Speed(value, SpeedUnit.CentimeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromCentimetersPerSecond(double centimeterspersecond) - { - double value = (double) centimeterspersecond; - return new Speed(value, SpeedUnit.CentimeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromDecimetersPerMinutes(double decimetersperminutes) - { - double value = (double) decimetersperminutes; - return new Speed(value, SpeedUnit.DecimeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromDecimetersPerSecond(double decimeterspersecond) - { - double value = (double) decimeterspersecond; - return new Speed(value, SpeedUnit.DecimeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerHour(double feetperhour) - { - double value = (double) feetperhour; - return new Speed(value, SpeedUnit.FootPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerMinute(double feetperminute) - { - double value = (double) feetperminute; - return new Speed(value, SpeedUnit.FootPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromFeetPerSecond(double feetpersecond) - { - double value = (double) feetpersecond; - return new Speed(value, SpeedUnit.FootPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerHour(double inchesperhour) - { - double value = (double) inchesperhour; - return new Speed(value, SpeedUnit.InchPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerMinute(double inchesperminute) - { - double value = (double) inchesperminute; - return new Speed(value, SpeedUnit.InchPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromInchesPerSecond(double inchespersecond) - { - double value = (double) inchespersecond; - return new Speed(value, SpeedUnit.InchPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerHour(double kilometersperhour) - { - double value = (double) kilometersperhour; - return new Speed(value, SpeedUnit.KilometerPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerMinutes(double kilometersperminutes) - { - double value = (double) kilometersperminutes; - return new Speed(value, SpeedUnit.KilometerPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKilometersPerSecond(double kilometerspersecond) - { - double value = (double) kilometerspersecond; - return new Speed(value, SpeedUnit.KilometerPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromKnots(double knots) - { - double value = (double) knots; - return new Speed(value, SpeedUnit.Knot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMach(double mach) - { - double value = (double) mach; - return new Speed(value, SpeedUnit.Mach); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerHour(double metersperhour) - { - double value = (double) metersperhour; - return new Speed(value, SpeedUnit.MeterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerMinutes(double metersperminutes) - { - double value = (double) metersperminutes; - return new Speed(value, SpeedUnit.MeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMetersPerSecond(double meterspersecond) - { - double value = (double) meterspersecond; - return new Speed(value, SpeedUnit.MeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMicrometersPerMinutes(double micrometersperminutes) - { - double value = (double) micrometersperminutes; - return new Speed(value, SpeedUnit.MicrometerPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMicrometersPerSecond(double micrometerspersecond) - { - double value = (double) micrometerspersecond; - return new Speed(value, SpeedUnit.MicrometerPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMilesPerHour(double milesperhour) - { - double value = (double) milesperhour; - return new Speed(value, SpeedUnit.MilePerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerHour(double millimetersperhour) - { - double value = (double) millimetersperhour; - return new Speed(value, SpeedUnit.MillimeterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerMinutes(double millimetersperminutes) - { - double value = (double) millimetersperminutes; - return new Speed(value, SpeedUnit.MillimeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromMillimetersPerSecond(double millimeterspersecond) - { - double value = (double) millimeterspersecond; - return new Speed(value, SpeedUnit.MillimeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromNanometersPerMinutes(double nanometersperminutes) - { - double value = (double) nanometersperminutes; - return new Speed(value, SpeedUnit.NanometerPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromNanometersPerSecond(double nanometerspersecond) - { - double value = (double) nanometerspersecond; - return new Speed(value, SpeedUnit.NanometerPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerHour(double ussurveyfeetperhour) - { - double value = (double) ussurveyfeetperhour; - return new Speed(value, SpeedUnit.UsSurveyFootPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerMinute(double ussurveyfeetperminute) - { - double value = (double) ussurveyfeetperminute; - return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromUsSurveyFeetPerSecond(double ussurveyfeetpersecond) - { - double value = (double) ussurveyfeetpersecond; - return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerHour(double yardsperhour) - { - double value = (double) yardsperhour; - return new Speed(value, SpeedUnit.YardPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerMinute(double yardsperminute) - { - double value = (double) yardsperminute; - return new Speed(value, SpeedUnit.YardPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Speed FromYardsPerSecond(double yardspersecond) - { - double value = (double) yardspersecond; - return new Speed(value, SpeedUnit.YardPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Speed unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Speed From(double value, SpeedUnit fromUnit) - { - return new Speed((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Speed Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Speed Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Speed result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Speed result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static SpeedUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out SpeedUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out SpeedUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Speed objSpeed)) throw new ArgumentException("Expected type Speed.", nameof(obj)); - - return CompareTo(objSpeed); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Speed other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Speed objSpeed)) - return false; - - return Equals(objSpeed); - } - - public bool Equals(Speed other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Speed within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Speed. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((SpeedUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpeedUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Speed to another Speed with the unit representation . - /// - /// A Speed with the specified unit. - public Speed ToUnit(SpeedUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Speed(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case SpeedUnit.CentimeterPerHour: return (_value / 3600) * 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (_value / 60) * 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (_value / 60) * 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; - case SpeedUnit.FootPerHour: return _value * 0.3048 / 3600; - case SpeedUnit.FootPerMinute: return _value * 0.3048 / 60; - case SpeedUnit.FootPerSecond: return _value * 0.3048; - case SpeedUnit.InchPerHour: return (_value / 3600) * 2.54e-2; - case SpeedUnit.InchPerMinute: return (_value / 60) * 2.54e-2; - case SpeedUnit.InchPerSecond: return _value * 2.54e-2; - case SpeedUnit.KilometerPerHour: return (_value / 3600) * 1e3d; - case SpeedUnit.KilometerPerMinute: return (_value / 60) * 1e3d; - case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; - case SpeedUnit.Knot: return _value * 0.514444; - case SpeedUnit.Mach: return _value * 340.29; - case SpeedUnit.MeterPerHour: return _value / 3600; - case SpeedUnit.MeterPerMinute: return _value / 60; - case SpeedUnit.MeterPerSecond: return _value; - case SpeedUnit.MicrometerPerMinute: return (_value / 60) * 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; - case SpeedUnit.MilePerHour: return _value * 0.44704; - case SpeedUnit.MillimeterPerHour: return (_value / 3600) * 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (_value / 60) * 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; - case SpeedUnit.NanometerPerMinute: return (_value / 60) * 1e-9d; - case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (_value * 1200 / 3937) / 3600; - case SpeedUnit.UsSurveyFootPerMinute: return (_value * 1200 / 3937) / 60; - case SpeedUnit.UsSurveyFootPerSecond: return _value * 1200 / 3937; - case SpeedUnit.YardPerHour: return _value * 0.9144 / 3600; - case SpeedUnit.YardPerMinute: return _value * 0.9144 / 60; - case SpeedUnit.YardPerSecond: return _value * 0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(SpeedUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case SpeedUnit.CentimeterPerHour: return (baseUnitValue * 3600) / 1e-2d; - case SpeedUnit.CentimeterPerMinute: return (baseUnitValue * 60) / 1e-2d; - case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; - case SpeedUnit.DecimeterPerMinute: return (baseUnitValue * 60) / 1e-1d; - case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; - case SpeedUnit.FootPerHour: return baseUnitValue / 0.3048 * 3600; - case SpeedUnit.FootPerMinute: return baseUnitValue / 0.3048 * 60; - case SpeedUnit.FootPerSecond: return baseUnitValue / 0.3048; - case SpeedUnit.InchPerHour: return (baseUnitValue / 2.54e-2) * 3600; - case SpeedUnit.InchPerMinute: return (baseUnitValue / 2.54e-2) * 60; - case SpeedUnit.InchPerSecond: return baseUnitValue / 2.54e-2; - case SpeedUnit.KilometerPerHour: return (baseUnitValue * 3600) / 1e3d; - case SpeedUnit.KilometerPerMinute: return (baseUnitValue * 60) / 1e3d; - case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; - case SpeedUnit.Knot: return baseUnitValue / 0.514444; - case SpeedUnit.Mach: return baseUnitValue / 340.29; - case SpeedUnit.MeterPerHour: return baseUnitValue * 3600; - case SpeedUnit.MeterPerMinute: return baseUnitValue * 60; - case SpeedUnit.MeterPerSecond: return baseUnitValue; - case SpeedUnit.MicrometerPerMinute: return (baseUnitValue * 60) / 1e-6d; - case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; - case SpeedUnit.MilePerHour: return baseUnitValue / 0.44704; - case SpeedUnit.MillimeterPerHour: return (baseUnitValue * 3600) / 1e-3d; - case SpeedUnit.MillimeterPerMinute: return (baseUnitValue * 60) / 1e-3d; - case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; - case SpeedUnit.NanometerPerMinute: return (baseUnitValue * 60) / 1e-9d; - case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; - case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue * 3937 / 1200) * 3600; - case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue * 3937 / 1200) * 60; - case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue * 3937 / 1200; - case SpeedUnit.YardPerHour: return baseUnitValue / 0.9144 * 3600; - case SpeedUnit.YardPerMinute: return baseUnitValue / 0.9144 * 60; - case SpeedUnit.YardPerSecond: return baseUnitValue / 0.9144; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/StandardVolumeFlow.g.cs deleted file mode 100644 index f04bdf0ec0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ /dev/null @@ -1,745 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class StandardVolumeFlow : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly StandardVolumeFlowUnit? _unit; - - static StandardVolumeFlow() - { - BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); - BaseUnit = StandardVolumeFlowUnit.StandardCubicMeterPerSecond; - MaxValue = new StandardVolumeFlow(double.MaxValue, BaseUnit); - MinValue = new StandardVolumeFlow(double.MinValue, BaseUnit); - QuantityType = QuantityType.StandardVolumeFlow; - Units = Enum.GetValues(typeof(StandardVolumeFlowUnit)).Cast().Except(new StandardVolumeFlowUnit[]{ StandardVolumeFlowUnit.Undefined }).ToArray(); - Zero = new StandardVolumeFlow(0, BaseUnit); - Info = new QuantityInfo(QuantityType.StandardVolumeFlow, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit StandardCubicMeterPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public StandardVolumeFlow() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private StandardVolumeFlow(double value, StandardVolumeFlowUnit unit) - { - if (unit == StandardVolumeFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of StandardVolumeFlow, which is StandardCubicMeterPerSecond. All conversions go via this value. - /// - public static StandardVolumeFlowUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of StandardVolumeFlow - /// - public static StandardVolumeFlow MaxValue { get; } - - /// - /// Represents the smallest possible value of StandardVolumeFlow - /// - public static StandardVolumeFlow MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the StandardVolumeFlow quantity. - /// - public static StandardVolumeFlowUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit StandardCubicMeterPerSecond. - /// - public static StandardVolumeFlow Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public StandardVolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => StandardVolumeFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => StandardVolumeFlow.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicCentimetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicFeetPerHour => As(StandardVolumeFlowUnit.StandardCubicFootPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicFeetPerMinute => As(StandardVolumeFlowUnit.StandardCubicFootPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicFeetPerSecond => As(StandardVolumeFlowUnit.StandardCubicFootPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicMetersPerDay => As(StandardVolumeFlowUnit.StandardCubicMeterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicMetersPerHour => As(StandardVolumeFlowUnit.StandardCubicMeterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicMetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardCubicMetersPerSecond => As(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double StandardLitersPerMinute => As(StandardVolumeFlowUnit.StandardLiterPerMinute); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(StandardVolumeFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(StandardVolumeFlowUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(double standardcubiccentimetersperminute) - { - double value = (double) standardcubiccentimetersperminute; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicFeetPerHour(double standardcubicfeetperhour) - { - double value = (double) standardcubicfeetperhour; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicFeetPerMinute(double standardcubicfeetperminute) - { - double value = (double) standardcubicfeetperminute; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicFeetPerSecond(double standardcubicfeetpersecond) - { - double value = (double) standardcubicfeetpersecond; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicMetersPerDay(double standardcubicmetersperday) - { - double value = (double) standardcubicmetersperday; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicMetersPerHour(double standardcubicmetersperhour) - { - double value = (double) standardcubicmetersperhour; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicMetersPerMinute(double standardcubicmetersperminute) - { - double value = (double) standardcubicmetersperminute; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardCubicMetersPerSecond(double standardcubicmeterspersecond) - { - double value = (double) standardcubicmeterspersecond; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static StandardVolumeFlow FromStandardLitersPerMinute(double standardlitersperminute) - { - double value = (double) standardlitersperminute; - return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardLiterPerMinute); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// StandardVolumeFlow unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static StandardVolumeFlow From(double value, StandardVolumeFlowUnit fromUnit) - { - return new StandardVolumeFlow((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static StandardVolumeFlow Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static StandardVolumeFlow Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out StandardVolumeFlow result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out StandardVolumeFlow result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static StandardVolumeFlowUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static StandardVolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out StandardVolumeFlowUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out StandardVolumeFlowUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is StandardVolumeFlow objStandardVolumeFlow)) throw new ArgumentException("Expected type StandardVolumeFlow.", nameof(obj)); - - return CompareTo(objStandardVolumeFlow); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(StandardVolumeFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is StandardVolumeFlow objStandardVolumeFlow)) - return false; - - return Equals(objStandardVolumeFlow); - } - - public bool Equals(StandardVolumeFlow other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another StandardVolumeFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current StandardVolumeFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((StandardVolumeFlowUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(StandardVolumeFlowUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this StandardVolumeFlow to another StandardVolumeFlow with the unit representation . - /// - /// A StandardVolumeFlow with the specified unit. - public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new StandardVolumeFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute: return _value / 6e7; - case StandardVolumeFlowUnit.StandardCubicFootPerHour: return _value * 7.8657907199999087346816086183876e-6; - case StandardVolumeFlowUnit.StandardCubicFootPerMinute: return _value / 2118.88000326; - case StandardVolumeFlowUnit.StandardCubicFootPerSecond: return _value / 35.314666721; - case StandardVolumeFlowUnit.StandardCubicMeterPerDay: return _value / 86400; - case StandardVolumeFlowUnit.StandardCubicMeterPerHour: return _value / 3600; - case StandardVolumeFlowUnit.StandardCubicMeterPerMinute: return _value / 60; - case StandardVolumeFlowUnit.StandardCubicMeterPerSecond: return _value; - case StandardVolumeFlowUnit.StandardLiterPerMinute: return _value / 60000; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(StandardVolumeFlowUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute: return baseUnitValue * 6e7; - case StandardVolumeFlowUnit.StandardCubicFootPerHour: return baseUnitValue / 7.8657907199999087346816086183876e-6; - case StandardVolumeFlowUnit.StandardCubicFootPerMinute: return baseUnitValue * 2118.88000326; - case StandardVolumeFlowUnit.StandardCubicFootPerSecond: return baseUnitValue * 35.314666721; - case StandardVolumeFlowUnit.StandardCubicMeterPerDay: return baseUnitValue * 86400; - case StandardVolumeFlowUnit.StandardCubicMeterPerHour: return baseUnitValue * 3600; - case StandardVolumeFlowUnit.StandardCubicMeterPerMinute: return baseUnitValue * 60; - case StandardVolumeFlowUnit.StandardCubicMeterPerSecond: return baseUnitValue; - case StandardVolumeFlowUnit.StandardLiterPerMinute: return baseUnitValue * 60000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.g.cs deleted file mode 100644 index 3836ea4fe2..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Temperature.g.cs +++ /dev/null @@ -1,764 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Temperature : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureUnit? _unit; - - static Temperature() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); - BaseUnit = TemperatureUnit.Kelvin; - MaxValue = new Temperature(double.MaxValue, BaseUnit); - MinValue = new Temperature(double.MinValue, BaseUnit); - QuantityType = QuantityType.Temperature; - Units = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); - Zero = new Temperature(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Temperature, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Kelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Temperature() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Temperature(double value, TemperatureUnit unit) - { - if (unit == TemperatureUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Temperature, which is Kelvin. All conversions go via this value. - /// - public static TemperatureUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Temperature - /// - public static Temperature MaxValue { get; } - - /// - /// Represents the smallest possible value of Temperature - /// - public static Temperature MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Temperature quantity. - /// - public static TemperatureUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. - /// - public static Temperature Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Temperature.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Temperature.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesNewton => As(TemperatureUnit.DegreeNewton); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesRankine => As(TemperatureUnit.DegreeRankine); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); - - /// - /// Gets a value of this quantity converted into - /// - public double Kelvins => As(TemperatureUnit.Kelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double MillidegreesCelsius => As(TemperatureUnit.MillidegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double SolarTemperatures => As(TemperatureUnit.SolarTemperature); - - #endregion - - #region Static Methods - - 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⊙"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TemperatureUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesCelsius(double degreescelsius) - { - double value = (double) degreescelsius; - return new Temperature(value, TemperatureUnit.DegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesDelisle(double degreesdelisle) - { - double value = (double) degreesdelisle; - return new Temperature(value, TemperatureUnit.DegreeDelisle); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesFahrenheit(double degreesfahrenheit) - { - double value = (double) degreesfahrenheit; - return new Temperature(value, TemperatureUnit.DegreeFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesNewton(double degreesnewton) - { - double value = (double) degreesnewton; - return new Temperature(value, TemperatureUnit.DegreeNewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesRankine(double degreesrankine) - { - double value = (double) degreesrankine; - return new Temperature(value, TemperatureUnit.DegreeRankine); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesReaumur(double degreesreaumur) - { - double value = (double) degreesreaumur; - return new Temperature(value, TemperatureUnit.DegreeReaumur); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromDegreesRoemer(double degreesroemer) - { - double value = (double) degreesroemer; - return new Temperature(value, TemperatureUnit.DegreeRoemer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromKelvins(double kelvins) - { - double value = (double) kelvins; - return new Temperature(value, TemperatureUnit.Kelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromMillidegreesCelsius(double millidegreescelsius) - { - double value = (double) millidegreescelsius; - return new Temperature(value, TemperatureUnit.MillidegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Temperature FromSolarTemperatures(double solartemperatures) - { - double value = (double) solartemperatures; - return new Temperature(value, TemperatureUnit.SolarTemperature); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Temperature unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Temperature From(double value, TemperatureUnit fromUnit) - { - return new Temperature((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Temperature Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Temperature Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Temperature result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Temperature result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TemperatureUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TemperatureUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Temperature objTemperature)) throw new ArgumentException("Expected type Temperature.", nameof(obj)); - - return CompareTo(objTemperature); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Temperature other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Temperature objTemperature)) - return false; - - return Equals(objTemperature); - } - - public bool Equals(Temperature other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Temperature within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Temperature other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Temperature. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TemperatureUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Temperature to another Temperature with the unit representation . - /// - /// A Temperature with the specified unit. - public Temperature ToUnit(TemperatureUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Temperature(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureUnit.DegreeCelsius: return _value + 273.15; - case TemperatureUnit.DegreeDelisle: return _value * -2 / 3 + 373.15; - case TemperatureUnit.DegreeFahrenheit: return _value * 5 / 9 + 459.67 * 5 / 9; - case TemperatureUnit.DegreeNewton: return _value * 100 / 33 + 273.15; - case TemperatureUnit.DegreeRankine: return _value * 5 / 9; - case TemperatureUnit.DegreeReaumur: return _value * 5 / 4 + 273.15; - case TemperatureUnit.DegreeRoemer: return _value * 40 / 21 + 273.15 - 7.5 * 40d / 21; - case TemperatureUnit.Kelvin: return _value; - case TemperatureUnit.MillidegreeCelsius: return _value / 1000 + 273.15; - case TemperatureUnit.SolarTemperature: return _value * 5778; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; - case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15) * -3 / 2; - case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67 * 5 / 9) * 9 / 5; - case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15) * 33 / 100; - case TemperatureUnit.DegreeRankine: return baseUnitValue * 9 / 5; - case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15) * 4 / 5; - case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5 * 40d / 21)) * 21 / 40; - case TemperatureUnit.Kelvin: return baseUnitValue; - case TemperatureUnit.MillidegreeCelsius: return (baseUnitValue - 273.15) * 1000; - case TemperatureUnit.SolarTemperature: return baseUnitValue / 5778; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.g.cs deleted file mode 100644 index 7a2e1202dc..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ /dev/null @@ -1,764 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class TemperatureChangeRate : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureChangeRateUnit? _unit; - - static TemperatureChangeRate() - { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); - BaseUnit = TemperatureChangeRateUnit.DegreeCelsiusPerSecond; - MaxValue = new TemperatureChangeRate(double.MaxValue, BaseUnit); - MinValue = new TemperatureChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.TemperatureChangeRate; - Units = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); - Zero = new TemperatureChangeRate(0, BaseUnit); - Info = new QuantityInfo(QuantityType.TemperatureChangeRate, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public TemperatureChangeRate() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private TemperatureChangeRate(double value, TemperatureChangeRateUnit unit) - { - if (unit == TemperatureChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. - /// - public static TemperatureChangeRateUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of TemperatureChangeRate - /// - public static TemperatureChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of TemperatureChangeRate - /// - public static TemperatureChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the TemperatureChangeRate quantity. - /// - public static TemperatureChangeRateUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. - /// - public static TemperatureChangeRate Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => TemperatureChangeRate.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TemperatureChangeRateUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double centidegreescelsiuspersecond) - { - double value = (double) centidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double decadegreescelsiuspersecond) - { - double value = (double) decadegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double decidegreescelsiuspersecond) - { - double value = (double) decidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double degreescelsiusperminute) - { - double value = (double) degreescelsiusperminute; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double degreescelsiuspersecond) - { - double value = (double) degreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double hectodegreescelsiuspersecond) - { - double value = (double) hectodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double kilodegreescelsiuspersecond) - { - double value = (double) kilodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double microdegreescelsiuspersecond) - { - double value = (double) microdegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double millidegreescelsiuspersecond) - { - double value = (double) millidegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double nanodegreescelsiuspersecond) - { - double value = (double) nanodegreescelsiuspersecond; - return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureChangeRate unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit fromUnit) - { - return new TemperatureChangeRate((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureChangeRate Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureChangeRate Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out TemperatureChangeRate result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureChangeRateUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TemperatureChangeRateUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TemperatureChangeRate objTemperatureChangeRate)) throw new ArgumentException("Expected type TemperatureChangeRate.", nameof(obj)); - - return CompareTo(objTemperatureChangeRate); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(TemperatureChangeRate other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is TemperatureChangeRate objTemperatureChangeRate)) - return false; - - return Equals(objTemperatureChangeRate); - } - - public bool Equals(TemperatureChangeRate other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another TemperatureChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TemperatureChangeRateUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureChangeRateUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . - /// - /// A TemperatureChangeRate with the specified unit. - public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureChangeRate(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (_value) * 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (_value) * 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (_value) * 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return _value / 60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return _value; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (_value) * 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (_value) * 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (_value) * 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (_value) * 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (_value) * 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureChangeRateUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-2d; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (baseUnitValue) / 1e1d; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-1d; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return baseUnitValue * 60; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return baseUnitValue; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (baseUnitValue) / 1e2d; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (baseUnitValue) / 1e3d; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-6d; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-3d; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-9d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.g.cs deleted file mode 100644 index b001a8c82d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ /dev/null @@ -1,745 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Difference between two temperatures. The conversions are different than for Temperature. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class TemperatureDelta : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureDeltaUnit? _unit; - - static TemperatureDelta() - { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); - BaseUnit = TemperatureDeltaUnit.Kelvin; - MaxValue = new TemperatureDelta(double.MaxValue, BaseUnit); - MinValue = new TemperatureDelta(double.MinValue, BaseUnit); - QuantityType = QuantityType.TemperatureDelta; - Units = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); - Zero = new TemperatureDelta(0, BaseUnit); - Info = new QuantityInfo(QuantityType.TemperatureDelta, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit Kelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public TemperatureDelta() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private TemperatureDelta(double value, TemperatureDeltaUnit unit) - { - if (unit == TemperatureDeltaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. - /// - public static TemperatureDeltaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of TemperatureDelta - /// - public static TemperatureDelta MaxValue { get; } - - /// - /// Represents the smallest possible value of TemperatureDelta - /// - public static TemperatureDelta MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the TemperatureDelta quantity. - /// - public static TemperatureDeltaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. - /// - public static TemperatureDelta Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => TemperatureDelta.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); - - /// - /// Gets a value of this quantity converted into - /// - public double Kelvins => As(TemperatureDeltaUnit.Kelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double MillidegreesCelsius => As(TemperatureDeltaUnit.MillidegreeCelsius); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TemperatureDeltaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesCelsius(double degreescelsius) - { - double value = (double) degreescelsius; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesDelisle(double degreesdelisle) - { - double value = (double) degreesdelisle; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesFahrenheit(double degreesfahrenheit) - { - double value = (double) degreesfahrenheit; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesNewton(double degreesnewton) - { - double value = (double) degreesnewton; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRankine(double degreesrankine) - { - double value = (double) degreesrankine; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesReaumur(double degreesreaumur) - { - double value = (double) degreesreaumur; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromDegreesRoemer(double degreesroemer) - { - double value = (double) degreesroemer; - return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromKelvins(double kelvins) - { - double value = (double) kelvins; - return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureDelta FromMillidegreesCelsius(double millidegreescelsius) - { - double value = (double) millidegreescelsius; - return new TemperatureDelta(value, TemperatureDeltaUnit.MillidegreeCelsius); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureDelta unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) - { - return new TemperatureDelta((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureDelta Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureDelta Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureDelta result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out TemperatureDelta result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureDeltaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TemperatureDeltaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TemperatureDelta objTemperatureDelta)) throw new ArgumentException("Expected type TemperatureDelta.", nameof(obj)); - - return CompareTo(objTemperatureDelta); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(TemperatureDelta other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is TemperatureDelta objTemperatureDelta)) - return false; - - return Equals(objTemperatureDelta); - } - - public bool Equals(TemperatureDelta other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another TemperatureDelta within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureDelta. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TemperatureDeltaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureDeltaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation . - /// - /// A TemperatureDelta with the specified unit. - public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureDelta(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return _value; - case TemperatureDeltaUnit.DegreeDelisle: return _value * -2 / 3; - case TemperatureDeltaUnit.DegreeFahrenheit: return _value * 5 / 9; - case TemperatureDeltaUnit.DegreeNewton: return _value * 100 / 33; - case TemperatureDeltaUnit.DegreeRankine: return _value * 5 / 9; - case TemperatureDeltaUnit.DegreeReaumur: return _value * 5 / 4; - case TemperatureDeltaUnit.DegreeRoemer: return _value * 40 / 21; - case TemperatureDeltaUnit.Kelvin: return _value; - case TemperatureDeltaUnit.MillidegreeCelsius: return (_value) * 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureDeltaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; - case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue * -3 / 2; - case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue * 9 / 5; - case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue * 33 / 100; - case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue * 9 / 5; - case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue * 4 / 5; - case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue * 21 / 40; - case TemperatureDeltaUnit.Kelvin: return baseUnitValue; - case TemperatureDeltaUnit.MillidegreeCelsius: return (baseUnitValue) / 1e-3d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureGradient.g.cs deleted file mode 100644 index 507be0b601..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ /dev/null @@ -1,650 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The rate of change of temperature with displacement in a given direction (as with increase of height) - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class TemperatureGradient : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TemperatureGradientUnit? _unit; - - static TemperatureGradient() - { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); - BaseUnit = TemperatureGradientUnit.KelvinPerMeter; - MaxValue = new TemperatureGradient(double.MaxValue, BaseUnit); - MinValue = new TemperatureGradient(double.MinValue, BaseUnit); - QuantityType = QuantityType.TemperatureGradient; - Units = Enum.GetValues(typeof(TemperatureGradientUnit)).Cast().Except(new TemperatureGradientUnit[]{ TemperatureGradientUnit.Undefined }).ToArray(); - Zero = new TemperatureGradient(0, BaseUnit); - Info = new QuantityInfo(QuantityType.TemperatureGradient, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit KelvinPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public TemperatureGradient() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private TemperatureGradient(double value, TemperatureGradientUnit unit) - { - if (unit == TemperatureGradientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of TemperatureGradient, which is KelvinPerMeter. All conversions go via this value. - /// - public static TemperatureGradientUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of TemperatureGradient - /// - public static TemperatureGradient MaxValue { get; } - - /// - /// Represents the smallest possible value of TemperatureGradient - /// - public static TemperatureGradient MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the TemperatureGradient quantity. - /// - public static TemperatureGradientUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit KelvinPerMeter. - /// - public static TemperatureGradient Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TemperatureGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => TemperatureGradient.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TemperatureGradient.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelciusPerKilometer => As(TemperatureGradientUnit.DegreeCelsiusPerKilometer); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesCelciusPerMeter => As(TemperatureGradientUnit.DegreeCelsiusPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double DegreesFahrenheitPerFoot => As(TemperatureGradientUnit.DegreeFahrenheitPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KelvinsPerMeter => As(TemperatureGradientUnit.KelvinPerMeter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TemperatureGradientUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TemperatureGradientUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureGradient FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) - { - double value = (double) degreescelciusperkilometer; - return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerKilometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureGradient FromDegreesCelciusPerMeter(double degreescelciuspermeter) - { - double value = (double) degreescelciuspermeter; - return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureGradient FromDegreesFahrenheitPerFoot(double degreesfahrenheitperfoot) - { - double value = (double) degreesfahrenheitperfoot; - return new TemperatureGradient(value, TemperatureGradientUnit.DegreeFahrenheitPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TemperatureGradient FromKelvinsPerMeter(double kelvinspermeter) - { - double value = (double) kelvinspermeter; - return new TemperatureGradient(value, TemperatureGradientUnit.KelvinPerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TemperatureGradient unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TemperatureGradient From(double value, TemperatureGradientUnit fromUnit) - { - return new TemperatureGradient((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TemperatureGradient Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureGradient Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TemperatureGradient result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out TemperatureGradient result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TemperatureGradientUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TemperatureGradientUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TemperatureGradientUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TemperatureGradientUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TemperatureGradient objTemperatureGradient)) throw new ArgumentException("Expected type TemperatureGradient.", nameof(obj)); - - return CompareTo(objTemperatureGradient); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(TemperatureGradient other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is TemperatureGradient objTemperatureGradient)) - return false; - - return Equals(objTemperatureGradient); - } - - public bool Equals(TemperatureGradient other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another TemperatureGradient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureGradient. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TemperatureGradientUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureGradientUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TemperatureGradient to another TemperatureGradient with the unit representation . - /// - /// A TemperatureGradient with the specified unit. - public TemperatureGradient ToUnit(TemperatureGradientUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TemperatureGradient(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TemperatureGradientUnit.DegreeCelsiusPerKilometer: return _value / 1e3; - case TemperatureGradientUnit.DegreeCelsiusPerMeter: return _value; - case TemperatureGradientUnit.DegreeFahrenheitPerFoot: return (_value / 0.3048) * 5 / 9; - case TemperatureGradientUnit.KelvinPerMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TemperatureGradientUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TemperatureGradientUnit.DegreeCelsiusPerKilometer: return baseUnitValue * 1e3; - case TemperatureGradientUnit.DegreeCelsiusPerMeter: return baseUnitValue; - case TemperatureGradientUnit.DegreeFahrenheitPerFoot: return (baseUnitValue * 0.3048) * 9 / 5; - case TemperatureGradientUnit.KelvinPerMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.g.cs deleted file mode 100644 index 336602f50a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ /dev/null @@ -1,615 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Thermal conductivity is the property of a material to conduct heat. - /// - /// - /// https://en.wikipedia.org/wiki/Thermal_Conductivity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ThermalConductivity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ThermalConductivityUnit? _unit; - - static ThermalConductivity() - { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); - BaseUnit = ThermalConductivityUnit.WattPerMeterKelvin; - MaxValue = new ThermalConductivity(double.MaxValue, BaseUnit); - MinValue = new ThermalConductivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ThermalConductivity; - Units = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); - Zero = new ThermalConductivity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ThermalConductivity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit WattPerMeterKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ThermalConductivity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ThermalConductivity(double value, ThermalConductivityUnit unit) - { - if (unit == ThermalConductivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. - /// - public static ThermalConductivityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ThermalConductivity - /// - public static ThermalConductivity MaxValue { get; } - - /// - /// Represents the smallest possible value of ThermalConductivity - /// - public static ThermalConductivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ThermalConductivity quantity. - /// - public static ThermalConductivityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. - /// - public static ThermalConductivity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ThermalConductivity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ThermalConductivityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalConductivity FromBtusPerHourFootFahrenheit(double btusperhourfootfahrenheit) - { - double value = (double) btusperhourfootfahrenheit; - return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalConductivity FromWattsPerMeterKelvin(double wattspermeterkelvin) - { - double value = (double) wattspermeterkelvin; - return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ThermalConductivity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ThermalConductivity From(double value, ThermalConductivityUnit fromUnit) - { - return new ThermalConductivity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ThermalConductivity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ThermalConductivity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ThermalConductivity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ThermalConductivity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalConductivityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ThermalConductivityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ThermalConductivity objThermalConductivity)) throw new ArgumentException("Expected type ThermalConductivity.", nameof(obj)); - - return CompareTo(objThermalConductivity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ThermalConductivity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ThermalConductivity objThermalConductivity)) - return false; - - return Equals(objThermalConductivity); - } - - public bool Equals(ThermalConductivity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ThermalConductivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ThermalConductivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalConductivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ThermalConductivityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalConductivityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . - /// - /// A ThermalConductivity with the specified unit. - public ThermalConductivity ToUnit(ThermalConductivityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ThermalConductivity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return _value * 1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ThermalConductivityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ThermalConductivityUnit.BtuPerHourFootFahrenheit: return baseUnitValue / 1.73073467; - case ThermalConductivityUnit.WattPerMeterKelvin: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.g.cs deleted file mode 100644 index 319e2b5779..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/ThermalResistance.g.cs +++ /dev/null @@ -1,688 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class ThermalResistance : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly ThermalResistanceUnit? _unit; - - static ThermalResistance() - { - BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); - BaseUnit = ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; - MaxValue = new ThermalResistance(double.MaxValue, BaseUnit); - MinValue = new ThermalResistance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ThermalResistance; - Units = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); - Zero = new ThermalResistance(0, BaseUnit); - Info = new QuantityInfo(QuantityType.ThermalResistance, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public ThermalResistance() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private ThermalResistance(double value, ThermalResistanceUnit unit) - { - if (unit == ThermalResistanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. - /// - public static ThermalResistanceUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of ThermalResistance - /// - public static ThermalResistance MaxValue { get; } - - /// - /// Represents the smallest possible value of ThermalResistance - /// - public static ThermalResistance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the ThermalResistance quantity. - /// - public static ThermalResistanceUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. - /// - public static ThermalResistance Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => ThermalResistance.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - - /// - /// Gets a value of this quantity converted into - /// - public double SquareMeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareMeterKelvinPerWatt); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ThermalResistanceUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(double hoursquarefeetdegreesfahrenheitperbtu) - { - double value = (double) hoursquarefeetdegreesfahrenheitperbtu; - return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double squarecentimeterhourdegreescelsiusperkilocalorie) - { - double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; - return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(double squarecentimeterkelvinsperwatt) - { - double value = (double) squarecentimeterkelvinsperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(double squaremeterdegreescelsiusperwatt) - { - double value = (double) squaremeterdegreescelsiusperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(double squaremeterkelvinsperkilowatt) - { - double value = (double) squaremeterkelvinsperkilowatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static ThermalResistance FromSquareMeterKelvinsPerWatt(double squaremeterkelvinsperwatt) - { - double value = (double) squaremeterkelvinsperwatt; - return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerWatt); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// ThermalResistance unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static ThermalResistance From(double value, ThermalResistanceUnit fromUnit) - { - return new ThermalResistance((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static ThermalResistance Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ThermalResistance Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out ThermalResistance result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out ThermalResistance result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ThermalResistanceUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out ThermalResistanceUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ThermalResistance objThermalResistance)) throw new ArgumentException("Expected type ThermalResistance.", nameof(obj)); - - return CompareTo(objThermalResistance); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(ThermalResistance other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is ThermalResistance objThermalResistance)) - return false; - - return Equals(objThermalResistance); - } - - public bool Equals(ThermalResistance other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another ThermalResistance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(ThermalResistance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalResistance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((ThermalResistanceUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalResistanceUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this ThermalResistance to another ThermalResistance with the unit representation . - /// - /// A ThermalResistance with the specified unit. - public ThermalResistance ToUnit(ThermalResistanceUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new ThermalResistance(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value * 176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value * 0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value * 0.1; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value * 1000.0; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; - case ThermalResistanceUnit.SquareMeterKelvinPerWatt: return _value * 1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(ThermalResistanceUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue / 176.1121482159839; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue / 0.0859779507590433; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue / 0.1; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue / 1000.0; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; - case ThermalResistanceUnit.SquareMeterKelvinPerWatt: return baseUnitValue / 1000; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.g.cs deleted file mode 100644 index 4cb95ff132..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Torque.g.cs +++ /dev/null @@ -1,1052 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Torque : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TorqueUnit? _unit; - - static Torque() - { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = TorqueUnit.NewtonMeter; - MaxValue = new Torque(double.MaxValue, BaseUnit); - MinValue = new Torque(double.MinValue, BaseUnit); - QuantityType = QuantityType.Torque; - Units = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); - Zero = new Torque(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Torque, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Torque() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Torque(double value, TorqueUnit unit) - { - if (unit == TorqueUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. - /// - public static TorqueUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Torque - /// - public static Torque MaxValue { get; } - - /// - /// Represents the smallest possible value of Torque - /// - public static Torque MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Torque quantity. - /// - public static TorqueUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. - /// - public static Torque Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Torque.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Torque.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double GramForceCentimeters => As(TorqueUnit.GramForceCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramForceMeters => As(TorqueUnit.GramForceMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double GramForceMillimeters => As(TorqueUnit.GramForceMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMeters => As(TorqueUnit.NewtonMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundalFeet => As(TorqueUnit.PoundalFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceInches => As(TorqueUnit.PoundForceInch); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TorqueUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromGramForceCentimeters(double gramforcecentimeters) - { - double value = (double) gramforcecentimeters; - return new Torque(value, TorqueUnit.GramForceCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromGramForceMeters(double gramforcemeters) - { - double value = (double) gramforcemeters; - return new Torque(value, TorqueUnit.GramForceMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromGramForceMillimeters(double gramforcemillimeters) - { - double value = (double) gramforcemillimeters; - return new Torque(value, TorqueUnit.GramForceMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceCentimeters(double kilogramforcecentimeters) - { - double value = (double) kilogramforcecentimeters; - return new Torque(value, TorqueUnit.KilogramForceCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceMeters(double kilogramforcemeters) - { - double value = (double) kilogramforcemeters; - return new Torque(value, TorqueUnit.KilogramForceMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilogramForceMillimeters(double kilogramforcemillimeters) - { - double value = (double) kilogramforcemillimeters; - return new Torque(value, TorqueUnit.KilogramForceMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonCentimeters(double kilonewtoncentimeters) - { - double value = (double) kilonewtoncentimeters; - return new Torque(value, TorqueUnit.KilonewtonCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonMeters(double kilonewtonmeters) - { - double value = (double) kilonewtonmeters; - return new Torque(value, TorqueUnit.KilonewtonMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilonewtonMillimeters(double kilonewtonmillimeters) - { - double value = (double) kilonewtonmillimeters; - return new Torque(value, TorqueUnit.KilonewtonMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilopoundForceFeet(double kilopoundforcefeet) - { - double value = (double) kilopoundforcefeet; - return new Torque(value, TorqueUnit.KilopoundForceFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromKilopoundForceInches(double kilopoundforceinches) - { - double value = (double) kilopoundforceinches; - return new Torque(value, TorqueUnit.KilopoundForceInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonCentimeters(double meganewtoncentimeters) - { - double value = (double) meganewtoncentimeters; - return new Torque(value, TorqueUnit.MeganewtonCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonMeters(double meganewtonmeters) - { - double value = (double) meganewtonmeters; - return new Torque(value, TorqueUnit.MeganewtonMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMeganewtonMillimeters(double meganewtonmillimeters) - { - double value = (double) meganewtonmillimeters; - return new Torque(value, TorqueUnit.MeganewtonMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMegapoundForceFeet(double megapoundforcefeet) - { - double value = (double) megapoundforcefeet; - return new Torque(value, TorqueUnit.MegapoundForceFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromMegapoundForceInches(double megapoundforceinches) - { - double value = (double) megapoundforceinches; - return new Torque(value, TorqueUnit.MegapoundForceInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonCentimeters(double newtoncentimeters) - { - double value = (double) newtoncentimeters; - return new Torque(value, TorqueUnit.NewtonCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonMeters(double newtonmeters) - { - double value = (double) newtonmeters; - return new Torque(value, TorqueUnit.NewtonMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromNewtonMillimeters(double newtonmillimeters) - { - double value = (double) newtonmillimeters; - return new Torque(value, TorqueUnit.NewtonMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundalFeet(double poundalfeet) - { - double value = (double) poundalfeet; - return new Torque(value, TorqueUnit.PoundalFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundForceFeet(double poundforcefeet) - { - double value = (double) poundforcefeet; - return new Torque(value, TorqueUnit.PoundForceFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromPoundForceInches(double poundforceinches) - { - double value = (double) poundforceinches; - return new Torque(value, TorqueUnit.PoundForceInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceCentimeters(double tonneforcecentimeters) - { - double value = (double) tonneforcecentimeters; - return new Torque(value, TorqueUnit.TonneForceCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceMeters(double tonneforcemeters) - { - double value = (double) tonneforcemeters; - return new Torque(value, TorqueUnit.TonneForceMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Torque FromTonneForceMillimeters(double tonneforcemillimeters) - { - double value = (double) tonneforcemillimeters; - return new Torque(value, TorqueUnit.TonneForceMillimeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Torque unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Torque From(double value, TorqueUnit fromUnit) - { - return new Torque((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Torque Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Torque Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Torque result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Torque result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TorqueUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TorqueUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TorqueUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Torque objTorque)) throw new ArgumentException("Expected type Torque.", nameof(obj)); - - return CompareTo(objTorque); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Torque other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Torque objTorque)) - return false; - - return Equals(objTorque); - } - - public bool Equals(Torque other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Torque within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Torque other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Torque. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TorqueUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorqueUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Torque to another Torque with the unit representation . - /// - /// A Torque with the specified unit. - public Torque ToUnit(TorqueUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Torque(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TorqueUnit.GramForceCentimeter: return _value * 9.80665e-5; - case TorqueUnit.GramForceMeter: return _value * 9.80665e-3; - case TorqueUnit.GramForceMillimeter: return _value * 9.80665e-6; - case TorqueUnit.KilogramForceCentimeter: return _value * 9.80665e-2; - case TorqueUnit.KilogramForceMeter: return _value * 9.80665; - case TorqueUnit.KilogramForceMillimeter: return _value * 9.80665e-3; - case TorqueUnit.KilonewtonCentimeter: return (_value * 0.01) * 1e3d; - case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (_value * 0.001) * 1e3d; - case TorqueUnit.KilopoundForceFoot: return (_value * 1.3558179483314) * 1e3d; - case TorqueUnit.KilopoundForceInch: return (_value * 1.129848290276167e-1) * 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (_value * 0.01) * 1e6d; - case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (_value * 0.001) * 1e6d; - case TorqueUnit.MegapoundForceFoot: return (_value * 1.3558179483314) * 1e6d; - case TorqueUnit.MegapoundForceInch: return (_value * 1.129848290276167e-1) * 1e6d; - case TorqueUnit.NewtonCentimeter: return _value * 0.01; - case TorqueUnit.NewtonMeter: return _value; - case TorqueUnit.NewtonMillimeter: return _value * 0.001; - case TorqueUnit.PoundalFoot: return _value * 4.21401100938048e-2; - case TorqueUnit.PoundForceFoot: return _value * 1.3558179483314; - case TorqueUnit.PoundForceInch: return _value * 1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return _value * 9.80665e1; - case TorqueUnit.TonneForceMeter: return _value * 9.80665e3; - case TorqueUnit.TonneForceMillimeter: return _value * 9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TorqueUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TorqueUnit.GramForceCentimeter: return baseUnitValue / 9.80665e-5; - case TorqueUnit.GramForceMeter: return baseUnitValue / 9.80665e-3; - case TorqueUnit.GramForceMillimeter: return baseUnitValue / 9.80665e-6; - case TorqueUnit.KilogramForceCentimeter: return baseUnitValue / 9.80665e-2; - case TorqueUnit.KilogramForceMeter: return baseUnitValue / 9.80665; - case TorqueUnit.KilogramForceMillimeter: return baseUnitValue / 9.80665e-3; - case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue * 100) / 1e3d; - case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; - case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue * 1000) / 1e3d; - case TorqueUnit.KilopoundForceFoot: return (baseUnitValue / 1.3558179483314) / 1e3d; - case TorqueUnit.KilopoundForceInch: return (baseUnitValue / 1.129848290276167e-1) / 1e3d; - case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue * 100) / 1e6d; - case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; - case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue * 1000) / 1e6d; - case TorqueUnit.MegapoundForceFoot: return (baseUnitValue / 1.3558179483314) / 1e6d; - case TorqueUnit.MegapoundForceInch: return (baseUnitValue / 1.129848290276167e-1) / 1e6d; - case TorqueUnit.NewtonCentimeter: return baseUnitValue * 100; - case TorqueUnit.NewtonMeter: return baseUnitValue; - case TorqueUnit.NewtonMillimeter: return baseUnitValue * 1000; - case TorqueUnit.PoundalFoot: return baseUnitValue / 4.21401100938048e-2; - case TorqueUnit.PoundForceFoot: return baseUnitValue / 1.3558179483314; - case TorqueUnit.PoundForceInch: return baseUnitValue / 1.129848290276167e-1; - case TorqueUnit.TonneForceCentimeter: return baseUnitValue / 9.80665e1; - case TorqueUnit.TonneForceMeter: return baseUnitValue / 9.80665e3; - case TorqueUnit.TonneForceMillimeter: return baseUnitValue / 9.80665; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TorquePerLength.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TorquePerLength.g.cs deleted file mode 100644 index 7e63d82a62..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/TorquePerLength.g.cs +++ /dev/null @@ -1,976 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The magnitude of torque per unit length. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class TorquePerLength : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TorquePerLengthUnit? _unit; - - static TorquePerLength() - { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - BaseUnit = TorquePerLengthUnit.NewtonMeterPerMeter; - MaxValue = new TorquePerLength(double.MaxValue, BaseUnit); - MinValue = new TorquePerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.TorquePerLength; - Units = Enum.GetValues(typeof(TorquePerLengthUnit)).Cast().Except(new TorquePerLengthUnit[]{ TorquePerLengthUnit.Undefined }).ToArray(); - Zero = new TorquePerLength(0, BaseUnit); - Info = new QuantityInfo(QuantityType.TorquePerLength, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NewtonMeterPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public TorquePerLength() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private TorquePerLength(double value, TorquePerLengthUnit unit) - { - if (unit == TorquePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of TorquePerLength, which is NewtonMeterPerMeter. All conversions go via this value. - /// - public static TorquePerLengthUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of TorquePerLength - /// - public static TorquePerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of TorquePerLength - /// - public static TorquePerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the TorquePerLength quantity. - /// - public static TorquePerLengthUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerMeter. - /// - public static TorquePerLength Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TorquePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => TorquePerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => TorquePerLength.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramForceCentimetersPerMeter => As(TorquePerLengthUnit.KilogramForceCentimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramForceMetersPerMeter => As(TorquePerLengthUnit.KilogramForceMeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilogramForceMillimetersPerMeter => As(TorquePerLengthUnit.KilogramForceMillimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonCentimetersPerMeter => As(TorquePerLengthUnit.KilonewtonCentimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMetersPerMeter => As(TorquePerLengthUnit.KilonewtonMeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilonewtonMillimetersPerMeter => As(TorquePerLengthUnit.KilonewtonMillimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundForceFeetPerFoot => As(TorquePerLengthUnit.KilopoundForceFootPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilopoundForceInchesPerFoot => As(TorquePerLengthUnit.KilopoundForceInchPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonCentimetersPerMeter => As(TorquePerLengthUnit.MeganewtonCentimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMetersPerMeter => As(TorquePerLengthUnit.MeganewtonMeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MeganewtonMillimetersPerMeter => As(TorquePerLengthUnit.MeganewtonMillimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundForceFeetPerFoot => As(TorquePerLengthUnit.MegapoundForceFootPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MegapoundForceInchesPerFoot => As(TorquePerLengthUnit.MegapoundForceInchPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonCentimetersPerMeter => As(TorquePerLengthUnit.NewtonCentimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMetersPerMeter => As(TorquePerLengthUnit.NewtonMeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double NewtonMillimetersPerMeter => As(TorquePerLengthUnit.NewtonMillimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceFeetPerFoot => As(TorquePerLengthUnit.PoundForceFootPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double PoundForceInchesPerFoot => As(TorquePerLengthUnit.PoundForceInchPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneForceCentimetersPerMeter => As(TorquePerLengthUnit.TonneForceCentimeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneForceMetersPerMeter => As(TorquePerLengthUnit.TonneForceMeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double TonneForceMillimetersPerMeter => As(TorquePerLengthUnit.TonneForceMillimeterPerMeter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TorquePerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TorquePerLengthUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilogramForceCentimetersPerMeter(double kilogramforcecentimeterspermeter) - { - double value = (double) kilogramforcecentimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceCentimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilogramForceMetersPerMeter(double kilogramforcemeterspermeter) - { - double value = (double) kilogramforcemeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceMeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilogramForceMillimetersPerMeter(double kilogramforcemillimeterspermeter) - { - double value = (double) kilogramforcemillimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceMillimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilonewtonCentimetersPerMeter(double kilonewtoncentimeterspermeter) - { - double value = (double) kilonewtoncentimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonCentimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilonewtonMetersPerMeter(double kilonewtonmeterspermeter) - { - double value = (double) kilonewtonmeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonMeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilonewtonMillimetersPerMeter(double kilonewtonmillimeterspermeter) - { - double value = (double) kilonewtonmillimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonMillimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilopoundForceFeetPerFoot(double kilopoundforcefeetperfoot) - { - double value = (double) kilopoundforcefeetperfoot; - return new TorquePerLength(value, TorquePerLengthUnit.KilopoundForceFootPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromKilopoundForceInchesPerFoot(double kilopoundforceinchesperfoot) - { - double value = (double) kilopoundforceinchesperfoot; - return new TorquePerLength(value, TorquePerLengthUnit.KilopoundForceInchPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromMeganewtonCentimetersPerMeter(double meganewtoncentimeterspermeter) - { - double value = (double) meganewtoncentimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonCentimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromMeganewtonMetersPerMeter(double meganewtonmeterspermeter) - { - double value = (double) meganewtonmeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonMeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromMeganewtonMillimetersPerMeter(double meganewtonmillimeterspermeter) - { - double value = (double) meganewtonmillimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonMillimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromMegapoundForceFeetPerFoot(double megapoundforcefeetperfoot) - { - double value = (double) megapoundforcefeetperfoot; - return new TorquePerLength(value, TorquePerLengthUnit.MegapoundForceFootPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromMegapoundForceInchesPerFoot(double megapoundforceinchesperfoot) - { - double value = (double) megapoundforceinchesperfoot; - return new TorquePerLength(value, TorquePerLengthUnit.MegapoundForceInchPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromNewtonCentimetersPerMeter(double newtoncentimeterspermeter) - { - double value = (double) newtoncentimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.NewtonCentimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromNewtonMetersPerMeter(double newtonmeterspermeter) - { - double value = (double) newtonmeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.NewtonMeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromNewtonMillimetersPerMeter(double newtonmillimeterspermeter) - { - double value = (double) newtonmillimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.NewtonMillimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromPoundForceFeetPerFoot(double poundforcefeetperfoot) - { - double value = (double) poundforcefeetperfoot; - return new TorquePerLength(value, TorquePerLengthUnit.PoundForceFootPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromPoundForceInchesPerFoot(double poundforceinchesperfoot) - { - double value = (double) poundforceinchesperfoot; - return new TorquePerLength(value, TorquePerLengthUnit.PoundForceInchPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromTonneForceCentimetersPerMeter(double tonneforcecentimeterspermeter) - { - double value = (double) tonneforcecentimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.TonneForceCentimeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromTonneForceMetersPerMeter(double tonneforcemeterspermeter) - { - double value = (double) tonneforcemeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.TonneForceMeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static TorquePerLength FromTonneForceMillimetersPerMeter(double tonneforcemillimeterspermeter) - { - double value = (double) tonneforcemillimeterspermeter; - return new TorquePerLength(value, TorquePerLengthUnit.TonneForceMillimeterPerMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// TorquePerLength unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static TorquePerLength From(double value, TorquePerLengthUnit fromUnit) - { - return new TorquePerLength((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static TorquePerLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TorquePerLength Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out TorquePerLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out TorquePerLength result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TorquePerLengthUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TorquePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TorquePerLengthUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TorquePerLengthUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TorquePerLength objTorquePerLength)) throw new ArgumentException("Expected type TorquePerLength.", nameof(obj)); - - return CompareTo(objTorquePerLength); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(TorquePerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is TorquePerLength objTorquePerLength)) - return false; - - return Equals(objTorquePerLength); - } - - public bool Equals(TorquePerLength other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another TorquePerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TorquePerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TorquePerLengthUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorquePerLengthUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this TorquePerLength to another TorquePerLength with the unit representation . - /// - /// A TorquePerLength with the specified unit. - public TorquePerLength ToUnit(TorquePerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new TorquePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TorquePerLengthUnit.KilogramForceCentimeterPerMeter: return _value * 0.0980665019960652; - case TorquePerLengthUnit.KilogramForceMeterPerMeter: return _value * 9.80665019960652; - case TorquePerLengthUnit.KilogramForceMillimeterPerMeter: return _value * 0.00980665019960652; - case TorquePerLengthUnit.KilonewtonCentimeterPerMeter: return (_value * 0.01) * 1e3d; - case TorquePerLengthUnit.KilonewtonMeterPerMeter: return (_value) * 1e3d; - case TorquePerLengthUnit.KilonewtonMillimeterPerMeter: return (_value * 0.001) * 1e3d; - case TorquePerLengthUnit.KilopoundForceFootPerFoot: return (_value * 4.44822161526) * 1e3d; - case TorquePerLengthUnit.KilopoundForceInchPerFoot: return (_value * 0.370685147638) * 1e3d; - case TorquePerLengthUnit.MeganewtonCentimeterPerMeter: return (_value * 0.01) * 1e6d; - case TorquePerLengthUnit.MeganewtonMeterPerMeter: return (_value) * 1e6d; - case TorquePerLengthUnit.MeganewtonMillimeterPerMeter: return (_value * 0.001) * 1e6d; - case TorquePerLengthUnit.MegapoundForceFootPerFoot: return (_value * 4.44822161526) * 1e6d; - case TorquePerLengthUnit.MegapoundForceInchPerFoot: return (_value * 0.370685147638) * 1e6d; - case TorquePerLengthUnit.NewtonCentimeterPerMeter: return _value * 0.01; - case TorquePerLengthUnit.NewtonMeterPerMeter: return _value; - case TorquePerLengthUnit.NewtonMillimeterPerMeter: return _value * 0.001; - case TorquePerLengthUnit.PoundForceFootPerFoot: return _value * 4.44822161526; - case TorquePerLengthUnit.PoundForceInchPerFoot: return _value * 0.370685147638; - case TorquePerLengthUnit.TonneForceCentimeterPerMeter: return _value * 98.0665019960652; - case TorquePerLengthUnit.TonneForceMeterPerMeter: return _value * 9806.65019960653; - case TorquePerLengthUnit.TonneForceMillimeterPerMeter: return _value * 9.80665019960652; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TorquePerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TorquePerLengthUnit.KilogramForceCentimeterPerMeter: return baseUnitValue * 10.1971619222242; - case TorquePerLengthUnit.KilogramForceMeterPerMeter: return baseUnitValue * 0.101971619222242; - case TorquePerLengthUnit.KilogramForceMillimeterPerMeter: return baseUnitValue * 101.971619222242; - case TorquePerLengthUnit.KilonewtonCentimeterPerMeter: return (baseUnitValue * 100) / 1e3d; - case TorquePerLengthUnit.KilonewtonMeterPerMeter: return (baseUnitValue) / 1e3d; - case TorquePerLengthUnit.KilonewtonMillimeterPerMeter: return (baseUnitValue * 1000) / 1e3d; - case TorquePerLengthUnit.KilopoundForceFootPerFoot: return (baseUnitValue / 4.44822161526) / 1e3d; - case TorquePerLengthUnit.KilopoundForceInchPerFoot: return (baseUnitValue / 0.370685147638) / 1e3d; - case TorquePerLengthUnit.MeganewtonCentimeterPerMeter: return (baseUnitValue * 100) / 1e6d; - case TorquePerLengthUnit.MeganewtonMeterPerMeter: return (baseUnitValue) / 1e6d; - case TorquePerLengthUnit.MeganewtonMillimeterPerMeter: return (baseUnitValue * 1000) / 1e6d; - case TorquePerLengthUnit.MegapoundForceFootPerFoot: return (baseUnitValue / 4.44822161526) / 1e6d; - case TorquePerLengthUnit.MegapoundForceInchPerFoot: return (baseUnitValue / 0.370685147638) / 1e6d; - case TorquePerLengthUnit.NewtonCentimeterPerMeter: return baseUnitValue * 100; - case TorquePerLengthUnit.NewtonMeterPerMeter: return baseUnitValue; - case TorquePerLengthUnit.NewtonMillimeterPerMeter: return baseUnitValue * 1000; - case TorquePerLengthUnit.PoundForceFootPerFoot: return baseUnitValue / 4.44822161526; - case TorquePerLengthUnit.PoundForceInchPerFoot: return baseUnitValue / 0.370685147638; - case TorquePerLengthUnit.TonneForceCentimeterPerMeter: return baseUnitValue * 0.0101971619222242; - case TorquePerLengthUnit.TonneForceMeterPerMeter: return baseUnitValue * 0.000101971619222242; - case TorquePerLengthUnit.TonneForceMillimeterPerMeter: return baseUnitValue * 0.101971619222242; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Turbidity.g.cs deleted file mode 100644 index 6dffba132e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Turbidity.g.cs +++ /dev/null @@ -1,596 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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. - /// - /// - /// https://en.wikipedia.org/wiki/Turbidity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Turbidity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly TurbidityUnit? _unit; - - static Turbidity() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = TurbidityUnit.NTU; - MaxValue = new Turbidity(double.MaxValue, BaseUnit); - MinValue = new Turbidity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Turbidity; - Units = Enum.GetValues(typeof(TurbidityUnit)).Cast().Except(new TurbidityUnit[]{ TurbidityUnit.Undefined }).ToArray(); - Zero = new Turbidity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Turbidity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit NTU. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Turbidity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Turbidity(double value, TurbidityUnit unit) - { - if (unit == TurbidityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Turbidity, which is NTU. All conversions go via this value. - /// - public static TurbidityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Turbidity - /// - public static Turbidity MaxValue { get; } - - /// - /// Represents the smallest possible value of Turbidity - /// - public static Turbidity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Turbidity quantity. - /// - public static TurbidityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit NTU. - /// - public static Turbidity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public TurbidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Turbidity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Turbidity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double NTU => As(TurbidityUnit.NTU); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(TurbidityUnit.NTU, new CultureInfo("en-US"), false, true, new string[]{"NTU"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(TurbidityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(TurbidityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Turbidity FromNTU(double ntu) - { - double value = (double) ntu; - return new Turbidity(value, TurbidityUnit.NTU); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Turbidity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Turbidity From(double value, TurbidityUnit fromUnit) - { - return new Turbidity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Turbidity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Turbidity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Turbidity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Turbidity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static TurbidityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static TurbidityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out TurbidityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out TurbidityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Turbidity objTurbidity)) throw new ArgumentException("Expected type Turbidity.", nameof(obj)); - - return CompareTo(objTurbidity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Turbidity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Turbidity objTurbidity)) - return false; - - return Equals(objTurbidity); - } - - public bool Equals(Turbidity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Turbidity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Turbidity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((TurbidityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TurbidityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Turbidity to another Turbidity with the unit representation . - /// - /// A Turbidity with the specified unit. - public Turbidity ToUnit(TurbidityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Turbidity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case TurbidityUnit.NTU: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(TurbidityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case TurbidityUnit.NTU: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.g.cs deleted file mode 100644 index 167fa714db..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VitaminA.g.cs +++ /dev/null @@ -1,593 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VitaminA : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VitaminAUnit? _unit; - - static VitaminA() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = VitaminAUnit.InternationalUnit; - MaxValue = new VitaminA(double.MaxValue, BaseUnit); - MinValue = new VitaminA(double.MinValue, BaseUnit); - QuantityType = QuantityType.VitaminA; - Units = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); - Zero = new VitaminA(0, BaseUnit); - Info = new QuantityInfo(QuantityType.VitaminA, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit InternationalUnit. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public VitaminA() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private VitaminA(double value, VitaminAUnit unit) - { - if (unit == VitaminAUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. - /// - public static VitaminAUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of VitaminA - /// - public static VitaminA MaxValue { get; } - - /// - /// Represents the smallest possible value of VitaminA - /// - public static VitaminA MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the VitaminA quantity. - /// - public static VitaminAUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. - /// - public static VitaminA Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => VitaminA.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VitaminA.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double InternationalUnits => As(VitaminAUnit.InternationalUnit); - - #endregion - - #region Static Methods - - internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) - { - unitAbbreviationsCache.PerformAbbreviationMapping(VitaminAUnit.InternationalUnit, new CultureInfo("en-US"), false, true, new string[]{"IU"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VitaminAUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VitaminA FromInternationalUnits(double internationalunits) - { - double value = (double) internationalunits; - return new VitaminA(value, VitaminAUnit.InternationalUnit); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VitaminA unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VitaminA From(double value, VitaminAUnit fromUnit) - { - return new VitaminA((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VitaminA Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VitaminA Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VitaminA result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out VitaminA result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VitaminAUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VitaminAUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VitaminAUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VitaminA objVitaminA)) throw new ArgumentException("Expected type VitaminA.", nameof(obj)); - - return CompareTo(objVitaminA); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(VitaminA other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is VitaminA objVitaminA)) - return false; - - return Equals(objVitaminA); - } - - public bool Equals(VitaminA other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VitaminA within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VitaminA. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VitaminAUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VitaminAUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VitaminA to another VitaminA with the unit representation . - /// - /// A VitaminA with the specified unit. - public VitaminA ToUnit(VitaminAUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VitaminA(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VitaminAUnit.InternationalUnit: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VitaminAUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VitaminAUnit.InternationalUnit: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.g.cs deleted file mode 100644 index 54913254f6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Volume.g.cs +++ /dev/null @@ -1,1609 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class Volume : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeUnit? _unit; - - static Volume() - { - BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); - BaseUnit = VolumeUnit.CubicMeter; - MaxValue = new Volume(double.MaxValue, BaseUnit); - MinValue = new Volume(double.MinValue, BaseUnit); - QuantityType = QuantityType.Volume; - Units = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); - Zero = new Volume(0, BaseUnit); - Info = new QuantityInfo(QuantityType.Volume, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CubicMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public Volume() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private Volume(double value, VolumeUnit unit) - { - if (unit == VolumeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of Volume, which is CubicMeter. All conversions go via this value. - /// - public static VolumeUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of Volume - /// - public static Volume MaxValue { get; } - - /// - /// Represents the smallest possible value of Volume - /// - public static Volume MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the Volume quantity. - /// - public static VolumeUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. - /// - public static Volume Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => Volume.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => Volume.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AcreFeet => As(VolumeUnit.AcreFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double AuTablespoons => As(VolumeUnit.AuTablespoon); - - /// - /// Gets a value of this quantity converted into - /// - public double BoardFeet => As(VolumeUnit.BoardFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double Centiliters => As(VolumeUnit.Centiliter); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicFeet => As(VolumeUnit.CubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicHectometers => As(VolumeUnit.CubicHectometer); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicInches => As(VolumeUnit.CubicInch); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicKilometers => As(VolumeUnit.CubicKilometer); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMeters => As(VolumeUnit.CubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMiles => As(VolumeUnit.CubicMile); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYards => As(VolumeUnit.CubicYard); - - /// - /// Gets a value of this quantity converted into - /// - public double Decaliters => As(VolumeUnit.Decaliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecausGallons => As(VolumeUnit.DecausGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double Deciliters => As(VolumeUnit.Deciliter); - - /// - /// Gets a value of this quantity converted into - /// - public double DeciusGallons => As(VolumeUnit.DeciusGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double Hectoliters => As(VolumeUnit.Hectoliter); - - /// - /// Gets a value of this quantity converted into - /// - public double HectousGallons => As(VolumeUnit.HectousGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); - - /// - /// Gets a value of this quantity converted into - /// - public double ImperialGallons => As(VolumeUnit.ImperialGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double ImperialOunces => As(VolumeUnit.ImperialOunce); - - /// - /// Gets a value of this quantity converted into - /// - public double ImperialPints => As(VolumeUnit.ImperialPint); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double Kiloliters => As(VolumeUnit.Kiloliter); - - /// - /// Gets a value of this quantity converted into - /// - public double KilousGallons => As(VolumeUnit.KilousGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double Liters => As(VolumeUnit.Liter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double Megaliters => As(VolumeUnit.Megaliter); - - /// - /// Gets a value of this quantity converted into - /// - public double MegausGallons => As(VolumeUnit.MegausGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double MetricCups => As(VolumeUnit.MetricCup); - - /// - /// Gets a value of this quantity converted into - /// - public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); - - /// - /// Gets a value of this quantity converted into - /// - public double Microliters => As(VolumeUnit.Microliter); - - /// - /// Gets a value of this quantity converted into - /// - public double Milliliters => As(VolumeUnit.Milliliter); - - /// - /// Gets a value of this quantity converted into - /// - public double OilBarrels => As(VolumeUnit.OilBarrel); - - /// - /// Gets a value of this quantity converted into - /// - public double UkTablespoons => As(VolumeUnit.UkTablespoon); - - /// - /// Gets a value of this quantity converted into - /// - public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); - - /// - /// Gets a value of this quantity converted into - /// - public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); - - /// - /// Gets a value of this quantity converted into - /// - public double UsGallons => As(VolumeUnit.UsGallon); - - /// - /// Gets a value of this quantity converted into - /// - public double UsLegalCups => As(VolumeUnit.UsLegalCup); - - /// - /// Gets a value of this quantity converted into - /// - public double UsOunces => As(VolumeUnit.UsOunce); - - /// - /// Gets a value of this quantity converted into - /// - public double UsPints => As(VolumeUnit.UsPint); - - /// - /// Gets a value of this quantity converted into - /// - public double UsQuarts => As(VolumeUnit.UsQuart); - - /// - /// Gets a value of this quantity converted into - /// - public double UsTablespoons => As(VolumeUnit.UsTablespoon); - - /// - /// Gets a value of this quantity converted into - /// - public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); - - #endregion - - #region Static Methods - - 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.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[]{""}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VolumeUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromAcreFeet(double acrefeet) - { - double value = (double) acrefeet; - return new Volume(value, VolumeUnit.AcreFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromAuTablespoons(double autablespoons) - { - double value = (double) autablespoons; - return new Volume(value, VolumeUnit.AuTablespoon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromBoardFeet(double boardfeet) - { - double value = (double) boardfeet; - return new Volume(value, VolumeUnit.BoardFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCentiliters(double centiliters) - { - double value = (double) centiliters; - return new Volume(value, VolumeUnit.Centiliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicCentimeters(double cubiccentimeters) - { - double value = (double) cubiccentimeters; - return new Volume(value, VolumeUnit.CubicCentimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicDecimeters(double cubicdecimeters) - { - double value = (double) cubicdecimeters; - return new Volume(value, VolumeUnit.CubicDecimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicFeet(double cubicfeet) - { - double value = (double) cubicfeet; - return new Volume(value, VolumeUnit.CubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicHectometers(double cubichectometers) - { - double value = (double) cubichectometers; - return new Volume(value, VolumeUnit.CubicHectometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicInches(double cubicinches) - { - double value = (double) cubicinches; - return new Volume(value, VolumeUnit.CubicInch); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicKilometers(double cubickilometers) - { - double value = (double) cubickilometers; - return new Volume(value, VolumeUnit.CubicKilometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMeters(double cubicmeters) - { - double value = (double) cubicmeters; - return new Volume(value, VolumeUnit.CubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMicrometers(double cubicmicrometers) - { - double value = (double) cubicmicrometers; - return new Volume(value, VolumeUnit.CubicMicrometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMiles(double cubicmiles) - { - double value = (double) cubicmiles; - return new Volume(value, VolumeUnit.CubicMile); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicMillimeters(double cubicmillimeters) - { - double value = (double) cubicmillimeters; - return new Volume(value, VolumeUnit.CubicMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromCubicYards(double cubicyards) - { - double value = (double) cubicyards; - return new Volume(value, VolumeUnit.CubicYard); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromDecaliters(double decaliters) - { - double value = (double) decaliters; - return new Volume(value, VolumeUnit.Decaliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromDecausGallons(double decausgallons) - { - double value = (double) decausgallons; - return new Volume(value, VolumeUnit.DecausGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromDeciliters(double deciliters) - { - double value = (double) deciliters; - return new Volume(value, VolumeUnit.Deciliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromDeciusGallons(double deciusgallons) - { - double value = (double) deciusgallons; - return new Volume(value, VolumeUnit.DeciusGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectocubicFeet(double hectocubicfeet) - { - double value = (double) hectocubicfeet; - return new Volume(value, VolumeUnit.HectocubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectocubicMeters(double hectocubicmeters) - { - double value = (double) hectocubicmeters; - return new Volume(value, VolumeUnit.HectocubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectoliters(double hectoliters) - { - double value = (double) hectoliters; - return new Volume(value, VolumeUnit.Hectoliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromHectousGallons(double hectousgallons) - { - double value = (double) hectousgallons; - return new Volume(value, VolumeUnit.HectousGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialBeerBarrels(double imperialbeerbarrels) - { - double value = (double) imperialbeerbarrels; - return new Volume(value, VolumeUnit.ImperialBeerBarrel); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialGallons(double imperialgallons) - { - double value = (double) imperialgallons; - return new Volume(value, VolumeUnit.ImperialGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialOunces(double imperialounces) - { - double value = (double) imperialounces; - return new Volume(value, VolumeUnit.ImperialOunce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromImperialPints(double imperialpints) - { - double value = (double) imperialpints; - return new Volume(value, VolumeUnit.ImperialPint); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilocubicFeet(double kilocubicfeet) - { - double value = (double) kilocubicfeet; - return new Volume(value, VolumeUnit.KilocubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilocubicMeters(double kilocubicmeters) - { - double value = (double) kilocubicmeters; - return new Volume(value, VolumeUnit.KilocubicMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKiloimperialGallons(double kiloimperialgallons) - { - double value = (double) kiloimperialgallons; - return new Volume(value, VolumeUnit.KiloimperialGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKiloliters(double kiloliters) - { - double value = (double) kiloliters; - return new Volume(value, VolumeUnit.Kiloliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromKilousGallons(double kilousgallons) - { - double value = (double) kilousgallons; - return new Volume(value, VolumeUnit.KilousGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromLiters(double liters) - { - double value = (double) liters; - return new Volume(value, VolumeUnit.Liter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegacubicFeet(double megacubicfeet) - { - double value = (double) megacubicfeet; - return new Volume(value, VolumeUnit.MegacubicFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegaimperialGallons(double megaimperialgallons) - { - double value = (double) megaimperialgallons; - return new Volume(value, VolumeUnit.MegaimperialGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegaliters(double megaliters) - { - double value = (double) megaliters; - return new Volume(value, VolumeUnit.Megaliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMegausGallons(double megausgallons) - { - double value = (double) megausgallons; - return new Volume(value, VolumeUnit.MegausGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMetricCups(double metriccups) - { - double value = (double) metriccups; - return new Volume(value, VolumeUnit.MetricCup); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMetricTeaspoons(double metricteaspoons) - { - double value = (double) metricteaspoons; - return new Volume(value, VolumeUnit.MetricTeaspoon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMicroliters(double microliters) - { - double value = (double) microliters; - return new Volume(value, VolumeUnit.Microliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromMilliliters(double milliliters) - { - double value = (double) milliliters; - return new Volume(value, VolumeUnit.Milliliter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromOilBarrels(double oilbarrels) - { - double value = (double) oilbarrels; - return new Volume(value, VolumeUnit.OilBarrel); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUkTablespoons(double uktablespoons) - { - double value = (double) uktablespoons; - return new Volume(value, VolumeUnit.UkTablespoon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsBeerBarrels(double usbeerbarrels) - { - double value = (double) usbeerbarrels; - return new Volume(value, VolumeUnit.UsBeerBarrel); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsCustomaryCups(double uscustomarycups) - { - double value = (double) uscustomarycups; - return new Volume(value, VolumeUnit.UsCustomaryCup); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsGallons(double usgallons) - { - double value = (double) usgallons; - return new Volume(value, VolumeUnit.UsGallon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsLegalCups(double uslegalcups) - { - double value = (double) uslegalcups; - return new Volume(value, VolumeUnit.UsLegalCup); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsOunces(double usounces) - { - double value = (double) usounces; - return new Volume(value, VolumeUnit.UsOunce); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsPints(double uspints) - { - double value = (double) uspints; - return new Volume(value, VolumeUnit.UsPint); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsQuarts(double usquarts) - { - double value = (double) usquarts; - return new Volume(value, VolumeUnit.UsQuart); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsTablespoons(double ustablespoons) - { - double value = (double) ustablespoons; - return new Volume(value, VolumeUnit.UsTablespoon); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static Volume FromUsTeaspoons(double usteaspoons) - { - double value = (double) usteaspoons; - return new Volume(value, VolumeUnit.UsTeaspoon); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Volume unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static Volume From(double value, VolumeUnit fromUnit) - { - return new Volume((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Volume Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static Volume Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out Volume result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Volume result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VolumeUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VolumeUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Volume objVolume)) throw new ArgumentException("Expected type Volume.", nameof(obj)); - - return CompareTo(objVolume); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(Volume other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is Volume objVolume)) - return false; - - return Equals(objVolume); - } - - public bool Equals(Volume other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another Volume within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Volume other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Volume. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VolumeUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this Volume to another Volume with the unit representation . - /// - /// A Volume with the specified unit. - public Volume ToUnit(VolumeUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new Volume(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumeUnit.AcreFoot: return _value / 0.000810714; - case VolumeUnit.AuTablespoon: return _value * 2e-5; - case VolumeUnit.BoardFoot: return _value * 2.3597372158e-3; - case VolumeUnit.Centiliter: return (_value / 1e3) * 1e-2d; - case VolumeUnit.CubicCentimeter: return _value / 1e6; - case VolumeUnit.CubicDecimeter: return _value / 1e3; - case VolumeUnit.CubicFoot: return _value * 2.8316846592e-2; - case VolumeUnit.CubicHectometer: return _value * 1e6; - case VolumeUnit.CubicInch: return _value * 1.6387 * 1e-5; - case VolumeUnit.CubicKilometer: return _value * 1e9; - case VolumeUnit.CubicMeter: return _value; - case VolumeUnit.CubicMicrometer: return _value / 1e18; - case VolumeUnit.CubicMile: return _value * 4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return _value / 1e9; - case VolumeUnit.CubicYard: return _value * 0.764554858; - case VolumeUnit.Decaliter: return (_value / 1e3) * 1e1d; - case VolumeUnit.DecausGallon: return (_value * 0.00378541) * 1e1d; - case VolumeUnit.Deciliter: return (_value / 1e3) * 1e-1d; - case VolumeUnit.DeciusGallon: return (_value * 0.00378541) * 1e-1d; - case VolumeUnit.HectocubicFoot: return (_value * 2.8316846592e-2) * 1e2d; - case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; - case VolumeUnit.Hectoliter: return (_value / 1e3) * 1e2d; - case VolumeUnit.HectousGallon: return (_value * 0.00378541) * 1e2d; - case VolumeUnit.ImperialBeerBarrel: return _value * 0.16365924; - case VolumeUnit.ImperialGallon: return _value * 0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return _value * 2.8413062499962901241875439064617e-5; - case VolumeUnit.ImperialPint: return _value * 5.6826125e-4; - case VolumeUnit.KilocubicFoot: return (_value * 2.8316846592e-2) * 1e3d; - case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; - case VolumeUnit.KiloimperialGallon: return (_value * 0.00454609000000181429905810072407) * 1e3d; - case VolumeUnit.Kiloliter: return (_value / 1e3) * 1e3d; - case VolumeUnit.KilousGallon: return (_value * 0.00378541) * 1e3d; - case VolumeUnit.Liter: return _value / 1e3; - case VolumeUnit.MegacubicFoot: return (_value * 2.8316846592e-2) * 1e6d; - case VolumeUnit.MegaimperialGallon: return (_value * 0.00454609000000181429905810072407) * 1e6d; - case VolumeUnit.Megaliter: return (_value / 1e3) * 1e6d; - case VolumeUnit.MegausGallon: return (_value * 0.00378541) * 1e6d; - case VolumeUnit.MetricCup: return _value * 0.00025; - case VolumeUnit.MetricTeaspoon: return _value * 0.5e-5; - case VolumeUnit.Microliter: return (_value / 1e3) * 1e-6d; - case VolumeUnit.Milliliter: return (_value / 1e3) * 1e-3d; - case VolumeUnit.OilBarrel: return _value * 0.158987294928; - case VolumeUnit.UkTablespoon: return _value * 1.5e-5; - case VolumeUnit.UsBeerBarrel: return _value * 0.1173477658; - case VolumeUnit.UsCustomaryCup: return _value * 0.0002365882365; - case VolumeUnit.UsGallon: return _value * 0.00378541; - case VolumeUnit.UsLegalCup: return _value * 0.00024; - case VolumeUnit.UsOunce: return _value * 2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return _value * 4.73176473e-4; - case VolumeUnit.UsQuart: return _value * 9.46352946e-4; - case VolumeUnit.UsTablespoon: return _value * 1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return _value * 4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeUnit.AcreFoot: return baseUnitValue * 0.000810714; - case VolumeUnit.AuTablespoon: return baseUnitValue / 2e-5; - case VolumeUnit.BoardFoot: return baseUnitValue / 2.3597372158e-3; - case VolumeUnit.Centiliter: return (baseUnitValue * 1e3) / 1e-2d; - case VolumeUnit.CubicCentimeter: return baseUnitValue * 1e6; - case VolumeUnit.CubicDecimeter: return baseUnitValue * 1e3; - case VolumeUnit.CubicFoot: return baseUnitValue / 2.8316846592e-2; - case VolumeUnit.CubicHectometer: return baseUnitValue / 1e6; - case VolumeUnit.CubicInch: return baseUnitValue / (1.6387 * 1e-5); - case VolumeUnit.CubicKilometer: return baseUnitValue / 1e9; - case VolumeUnit.CubicMeter: return baseUnitValue; - case VolumeUnit.CubicMicrometer: return baseUnitValue * 1e18; - case VolumeUnit.CubicMile: return baseUnitValue / 4.16818182544058e9; - case VolumeUnit.CubicMillimeter: return baseUnitValue * 1e9; - case VolumeUnit.CubicYard: return baseUnitValue / 0.764554858; - case VolumeUnit.Decaliter: return (baseUnitValue * 1e3) / 1e1d; - case VolumeUnit.DecausGallon: return (baseUnitValue / 0.00378541) / 1e1d; - case VolumeUnit.Deciliter: return (baseUnitValue * 1e3) / 1e-1d; - case VolumeUnit.DeciusGallon: return (baseUnitValue / 0.00378541) / 1e-1d; - case VolumeUnit.HectocubicFoot: return (baseUnitValue / 2.8316846592e-2) / 1e2d; - case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; - case VolumeUnit.Hectoliter: return (baseUnitValue * 1e3) / 1e2d; - case VolumeUnit.HectousGallon: return (baseUnitValue / 0.00378541) / 1e2d; - case VolumeUnit.ImperialBeerBarrel: return baseUnitValue / 0.16365924; - case VolumeUnit.ImperialGallon: return baseUnitValue / 0.00454609000000181429905810072407; - case VolumeUnit.ImperialOunce: return baseUnitValue / 2.8413062499962901241875439064617e-5; - case VolumeUnit.ImperialPint: return baseUnitValue / 5.6826125e-4; - case VolumeUnit.KilocubicFoot: return (baseUnitValue / 2.8316846592e-2) / 1e3d; - case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; - case VolumeUnit.KiloimperialGallon: return (baseUnitValue / 0.00454609000000181429905810072407) / 1e3d; - case VolumeUnit.Kiloliter: return (baseUnitValue * 1e3) / 1e3d; - case VolumeUnit.KilousGallon: return (baseUnitValue / 0.00378541) / 1e3d; - case VolumeUnit.Liter: return baseUnitValue * 1e3; - case VolumeUnit.MegacubicFoot: return (baseUnitValue / 2.8316846592e-2) / 1e6d; - case VolumeUnit.MegaimperialGallon: return (baseUnitValue / 0.00454609000000181429905810072407) / 1e6d; - case VolumeUnit.Megaliter: return (baseUnitValue * 1e3) / 1e6d; - case VolumeUnit.MegausGallon: return (baseUnitValue / 0.00378541) / 1e6d; - case VolumeUnit.MetricCup: return baseUnitValue / 0.00025; - case VolumeUnit.MetricTeaspoon: return baseUnitValue / 0.5e-5; - case VolumeUnit.Microliter: return (baseUnitValue * 1e3) / 1e-6d; - case VolumeUnit.Milliliter: return (baseUnitValue * 1e3) / 1e-3d; - case VolumeUnit.OilBarrel: return baseUnitValue / 0.158987294928; - case VolumeUnit.UkTablespoon: return baseUnitValue / 1.5e-5; - case VolumeUnit.UsBeerBarrel: return baseUnitValue / 0.1173477658; - case VolumeUnit.UsCustomaryCup: return baseUnitValue / 0.0002365882365; - case VolumeUnit.UsGallon: return baseUnitValue / 0.00378541; - case VolumeUnit.UsLegalCup: return baseUnitValue / 0.00024; - case VolumeUnit.UsOunce: return baseUnitValue / 2.957352956253760505068307980135e-5; - case VolumeUnit.UsPint: return baseUnitValue / 4.73176473e-4; - case VolumeUnit.UsQuart: return baseUnitValue / 9.46352946e-4; - case VolumeUnit.UsTablespoon: return baseUnitValue / 1.478676478125e-5; - case VolumeUnit.UsTeaspoon: return baseUnitValue / 4.92892159375e-6; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeConcentration.g.cs deleted file mode 100644 index 8f6a798947..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ /dev/null @@ -1,957 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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. - /// - /// - /// https://en.wikipedia.org/wiki/Concentration#Volume_concentration - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VolumeConcentration : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeConcentrationUnit? _unit; - - static VolumeConcentration() - { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = VolumeConcentrationUnit.DecimalFraction; - MaxValue = new VolumeConcentration(double.MaxValue, BaseUnit); - MinValue = new VolumeConcentration(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumeConcentration; - Units = Enum.GetValues(typeof(VolumeConcentrationUnit)).Cast().Except(new VolumeConcentrationUnit[]{ VolumeConcentrationUnit.Undefined }).ToArray(); - Zero = new VolumeConcentration(0, BaseUnit); - Info = new QuantityInfo(QuantityType.VolumeConcentration, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit DecimalFraction. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public VolumeConcentration() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private VolumeConcentration(double value, VolumeConcentrationUnit unit) - { - if (unit == VolumeConcentrationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of VolumeConcentration, which is DecimalFraction. All conversions go via this value. - /// - public static VolumeConcentrationUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of VolumeConcentration - /// - public static VolumeConcentration MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumeConcentration - /// - public static VolumeConcentration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the VolumeConcentration quantity. - /// - public static VolumeConcentrationUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. - /// - public static VolumeConcentration Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => VolumeConcentration.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumeConcentration.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentilitersPerLiter => As(VolumeConcentrationUnit.CentilitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double CentilitersPerMililiter => As(VolumeConcentrationUnit.CentilitersPerMililiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecilitersPerLiter => As(VolumeConcentrationUnit.DecilitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecilitersPerMililiter => As(VolumeConcentrationUnit.DecilitersPerMililiter); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimalFractions => As(VolumeConcentrationUnit.DecimalFraction); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerLiter => As(VolumeConcentrationUnit.LitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerMililiter => As(VolumeConcentrationUnit.LitersPerMililiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrolitersPerLiter => As(VolumeConcentrationUnit.MicrolitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrolitersPerMililiter => As(VolumeConcentrationUnit.MicrolitersPerMililiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillilitersPerLiter => As(VolumeConcentrationUnit.MillilitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double MillilitersPerMililiter => As(VolumeConcentrationUnit.MillilitersPerMililiter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanolitersPerLiter => As(VolumeConcentrationUnit.NanolitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double NanolitersPerMililiter => As(VolumeConcentrationUnit.NanolitersPerMililiter); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerBillion => As(VolumeConcentrationUnit.PartPerBillion); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerMillion => As(VolumeConcentrationUnit.PartPerMillion); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerThousand => As(VolumeConcentrationUnit.PartPerThousand); - - /// - /// Gets a value of this quantity converted into - /// - public double PartsPerTrillion => As(VolumeConcentrationUnit.PartPerTrillion); - - /// - /// Gets a value of this quantity converted into - /// - public double Percent => As(VolumeConcentrationUnit.Percent); - - /// - /// Gets a value of this quantity converted into - /// - public double PicolitersPerLiter => As(VolumeConcentrationUnit.PicolitersPerLiter); - - /// - /// Gets a value of this quantity converted into - /// - public double PicolitersPerMililiter => As(VolumeConcentrationUnit.PicolitersPerMililiter); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VolumeConcentrationUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VolumeConcentrationUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromCentilitersPerLiter(double centilitersperliter) - { - double value = (double) centilitersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.CentilitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromCentilitersPerMililiter(double centiliterspermililiter) - { - double value = (double) centiliterspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.CentilitersPerMililiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromDecilitersPerLiter(double decilitersperliter) - { - double value = (double) decilitersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.DecilitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromDecilitersPerMililiter(double deciliterspermililiter) - { - double value = (double) deciliterspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.DecilitersPerMililiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromDecimalFractions(double decimalfractions) - { - double value = (double) decimalfractions; - return new VolumeConcentration(value, VolumeConcentrationUnit.DecimalFraction); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromLitersPerLiter(double litersperliter) - { - double value = (double) litersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.LitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromLitersPerMililiter(double literspermililiter) - { - double value = (double) literspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.LitersPerMililiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromMicrolitersPerLiter(double microlitersperliter) - { - double value = (double) microlitersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.MicrolitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromMicrolitersPerMililiter(double microliterspermililiter) - { - double value = (double) microliterspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.MicrolitersPerMililiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromMillilitersPerLiter(double millilitersperliter) - { - double value = (double) millilitersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.MillilitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromMillilitersPerMililiter(double milliliterspermililiter) - { - double value = (double) milliliterspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.MillilitersPerMililiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromNanolitersPerLiter(double nanolitersperliter) - { - double value = (double) nanolitersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.NanolitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromNanolitersPerMililiter(double nanoliterspermililiter) - { - double value = (double) nanoliterspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.NanolitersPerMililiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPartsPerBillion(double partsperbillion) - { - double value = (double) partsperbillion; - return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerBillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPartsPerMillion(double partspermillion) - { - double value = (double) partspermillion; - return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerMillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPartsPerThousand(double partsperthousand) - { - double value = (double) partsperthousand; - return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerThousand); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPartsPerTrillion(double partspertrillion) - { - double value = (double) partspertrillion; - return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerTrillion); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPercent(double percent) - { - double value = (double) percent; - return new VolumeConcentration(value, VolumeConcentrationUnit.Percent); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPicolitersPerLiter(double picolitersperliter) - { - double value = (double) picolitersperliter; - return new VolumeConcentration(value, VolumeConcentrationUnit.PicolitersPerLiter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeConcentration FromPicolitersPerMililiter(double picoliterspermililiter) - { - double value = (double) picoliterspermililiter; - return new VolumeConcentration(value, VolumeConcentrationUnit.PicolitersPerMililiter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumeConcentration unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumeConcentration From(double value, VolumeConcentrationUnit fromUnit) - { - return new VolumeConcentration((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumeConcentration Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeConcentration Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumeConcentration result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out VolumeConcentration result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeConcentrationUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeConcentrationUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VolumeConcentrationUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VolumeConcentrationUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumeConcentration objVolumeConcentration)) throw new ArgumentException("Expected type VolumeConcentration.", nameof(obj)); - - return CompareTo(objVolumeConcentration); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(VolumeConcentration other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumeConcentration objVolumeConcentration)) - return false; - - return Equals(objVolumeConcentration); - } - - public bool Equals(VolumeConcentration other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VolumeConcentration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeConcentration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VolumeConcentrationUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeConcentrationUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumeConcentration to another VolumeConcentration with the unit representation . - /// - /// A VolumeConcentration with the specified unit. - public VolumeConcentration ToUnit(VolumeConcentrationUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumeConcentration(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumeConcentrationUnit.CentilitersPerLiter: return (_value) * 1e-2d; - case VolumeConcentrationUnit.CentilitersPerMililiter: return (_value / 1e-3) * 1e-2d; - case VolumeConcentrationUnit.DecilitersPerLiter: return (_value) * 1e-1d; - case VolumeConcentrationUnit.DecilitersPerMililiter: return (_value / 1e-3) * 1e-1d; - case VolumeConcentrationUnit.DecimalFraction: return _value; - case VolumeConcentrationUnit.LitersPerLiter: return _value; - case VolumeConcentrationUnit.LitersPerMililiter: return _value / 1e-3; - case VolumeConcentrationUnit.MicrolitersPerLiter: return (_value) * 1e-6d; - case VolumeConcentrationUnit.MicrolitersPerMililiter: return (_value / 1e-3) * 1e-6d; - case VolumeConcentrationUnit.MillilitersPerLiter: return (_value) * 1e-3d; - case VolumeConcentrationUnit.MillilitersPerMililiter: return (_value / 1e-3) * 1e-3d; - case VolumeConcentrationUnit.NanolitersPerLiter: return (_value) * 1e-9d; - case VolumeConcentrationUnit.NanolitersPerMililiter: return (_value / 1e-3) * 1e-9d; - case VolumeConcentrationUnit.PartPerBillion: return _value / 1e9; - case VolumeConcentrationUnit.PartPerMillion: return _value / 1e6; - case VolumeConcentrationUnit.PartPerThousand: return _value / 1e3; - case VolumeConcentrationUnit.PartPerTrillion: return _value / 1e12; - case VolumeConcentrationUnit.Percent: return _value / 1e2; - case VolumeConcentrationUnit.PicolitersPerLiter: return (_value) * 1e-12d; - case VolumeConcentrationUnit.PicolitersPerMililiter: return (_value / 1e-3) * 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeConcentrationUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeConcentrationUnit.CentilitersPerLiter: return (baseUnitValue) / 1e-2d; - case VolumeConcentrationUnit.CentilitersPerMililiter: return (baseUnitValue * 1e-3) / 1e-2d; - case VolumeConcentrationUnit.DecilitersPerLiter: return (baseUnitValue) / 1e-1d; - case VolumeConcentrationUnit.DecilitersPerMililiter: return (baseUnitValue * 1e-3) / 1e-1d; - case VolumeConcentrationUnit.DecimalFraction: return baseUnitValue; - case VolumeConcentrationUnit.LitersPerLiter: return baseUnitValue; - case VolumeConcentrationUnit.LitersPerMililiter: return baseUnitValue * 1e-3; - case VolumeConcentrationUnit.MicrolitersPerLiter: return (baseUnitValue) / 1e-6d; - case VolumeConcentrationUnit.MicrolitersPerMililiter: return (baseUnitValue * 1e-3) / 1e-6d; - case VolumeConcentrationUnit.MillilitersPerLiter: return (baseUnitValue) / 1e-3d; - case VolumeConcentrationUnit.MillilitersPerMililiter: return (baseUnitValue * 1e-3) / 1e-3d; - case VolumeConcentrationUnit.NanolitersPerLiter: return (baseUnitValue) / 1e-9d; - case VolumeConcentrationUnit.NanolitersPerMililiter: return (baseUnitValue * 1e-3) / 1e-9d; - case VolumeConcentrationUnit.PartPerBillion: return baseUnitValue * 1e9; - case VolumeConcentrationUnit.PartPerMillion: return baseUnitValue * 1e6; - case VolumeConcentrationUnit.PartPerThousand: return baseUnitValue * 1e3; - case VolumeConcentrationUnit.PartPerTrillion: return baseUnitValue * 1e12; - case VolumeConcentrationUnit.Percent: return baseUnitValue * 1e2; - case VolumeConcentrationUnit.PicolitersPerLiter: return (baseUnitValue) / 1e-12d; - case VolumeConcentrationUnit.PicolitersPerMililiter: return (baseUnitValue * 1e-3) / 1e-12d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.g.cs deleted file mode 100644 index 41827253dc..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlow.g.cs +++ /dev/null @@ -1,1779 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VolumeFlow : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeFlowUnit? _unit; - - static VolumeFlow() - { - BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); - BaseUnit = VolumeFlowUnit.CubicMeterPerSecond; - MaxValue = new VolumeFlow(double.MaxValue, BaseUnit); - MinValue = new VolumeFlow(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumeFlow; - Units = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); - Zero = new VolumeFlow(0, BaseUnit); - Info = new QuantityInfo(QuantityType.VolumeFlow, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CubicMeterPerSecond. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public VolumeFlow() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private VolumeFlow(double value, VolumeFlowUnit unit) - { - if (unit == VolumeFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. - /// - public static VolumeFlowUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of VolumeFlow - /// - public static VolumeFlow MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumeFlow - /// - public static VolumeFlow MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the VolumeFlow quantity. - /// - public static VolumeFlowUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. - /// - public static VolumeFlow Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => VolumeFlow.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double AcreFeetPerDay => As(VolumeFlowUnit.AcreFootPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double AcreFeetPerHour => As(VolumeFlowUnit.AcreFootPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double AcreFeetPerMinute => As(VolumeFlowUnit.AcreFootPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double AcreFeetPerSecond => As(VolumeFlowUnit.AcreFootPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double CentilitersPerDay => As(VolumeFlowUnit.CentiliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double CentilitersPerHour => As(VolumeFlowUnit.CentiliterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CentilitersPerSecond => As(VolumeFlowUnit.CentiliterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicCentimetersPerMinute => As(VolumeFlowUnit.CubicCentimeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerDay => As(VolumeFlowUnit.CubicMeterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYardsPerDay => As(VolumeFlowUnit.CubicYardPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double DecilitersPerDay => As(VolumeFlowUnit.DeciliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double DecilitersPerHour => As(VolumeFlowUnit.DeciliterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double DecilitersPerSecond => As(VolumeFlowUnit.DeciliterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilolitersPerDay => As(VolumeFlowUnit.KiloliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double KilolitersPerHour => As(VolumeFlowUnit.KiloliterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double KilolitersPerSecond => As(VolumeFlowUnit.KiloliterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerDay => As(VolumeFlowUnit.LiterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MegalitersPerDay => As(VolumeFlowUnit.MegaliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MegaukGallonsPerSecond => As(VolumeFlowUnit.MegaukGallonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrolitersPerDay => As(VolumeFlowUnit.MicroliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrolitersPerHour => As(VolumeFlowUnit.MicroliterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MicrolitersPerSecond => As(VolumeFlowUnit.MicroliterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillilitersPerDay => As(VolumeFlowUnit.MilliliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double MillilitersPerHour => As(VolumeFlowUnit.MilliliterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double NanolitersPerDay => As(VolumeFlowUnit.NanoliterPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double NanolitersPerHour => As(VolumeFlowUnit.NanoliterPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double NanolitersPerSecond => As(VolumeFlowUnit.NanoliterPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double OilBarrelsPerSecond => As(VolumeFlowUnit.OilBarrelPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double UkGallonsPerDay => As(VolumeFlowUnit.UkGallonPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double UkGallonsPerHour => As(VolumeFlowUnit.UkGallonPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double UkGallonsPerMinute => As(VolumeFlowUnit.UkGallonPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double UkGallonsPerSecond => As(VolumeFlowUnit.UkGallonPerSecond); - - /// - /// Gets a value of this quantity converted into - /// - public double UsGallonsPerDay => As(VolumeFlowUnit.UsGallonPerDay); - - /// - /// Gets a value of this quantity converted into - /// - public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); - - /// - /// Gets a value of this quantity converted into - /// - public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); - - /// - /// Gets a value of this quantity converted into - /// - public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); - - #endregion - - #region Static Methods - - 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.MillionUsGallonsPerDay, 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VolumeFlowUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromAcreFeetPerDay(double acrefeetperday) - { - double value = (double) acrefeetperday; - return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromAcreFeetPerHour(double acrefeetperhour) - { - double value = (double) acrefeetperhour; - return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromAcreFeetPerMinute(double acrefeetperminute) - { - double value = (double) acrefeetperminute; - return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromAcreFeetPerSecond(double acrefeetpersecond) - { - double value = (double) acrefeetpersecond; - return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCentilitersPerDay(double centilitersperday) - { - double value = (double) centilitersperday; - return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCentilitersPerHour(double centilitersperhour) - { - double value = (double) centilitersperhour; - return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCentilitersPerMinute(double centilitersperminute) - { - double value = (double) centilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCentilitersPerSecond(double centiliterspersecond) - { - double value = (double) centiliterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicCentimetersPerMinute(double cubiccentimetersperminute) - { - double value = (double) cubiccentimetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicCentimeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) - { - double value = (double) cubicdecimetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerHour(double cubicfeetperhour) - { - double value = (double) cubicfeetperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerMinute(double cubicfeetperminute) - { - double value = (double) cubicfeetperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicFeetPerSecond(double cubicfeetpersecond) - { - double value = (double) cubicfeetpersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerDay(double cubicmetersperday) - { - double value = (double) cubicmetersperday; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerHour(double cubicmetersperhour) - { - double value = (double) cubicmetersperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerMinute(double cubicmetersperminute) - { - double value = (double) cubicmetersperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMetersPerSecond(double cubicmeterspersecond) - { - double value = (double) cubicmeterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicMillimetersPerSecond(double cubicmillimeterspersecond) - { - double value = (double) cubicmillimeterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicMillimeterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerDay(double cubicyardsperday) - { - double value = (double) cubicyardsperday; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerHour(double cubicyardsperhour) - { - double value = (double) cubicyardsperhour; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerMinute(double cubicyardsperminute) - { - double value = (double) cubicyardsperminute; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromCubicYardsPerSecond(double cubicyardspersecond) - { - double value = (double) cubicyardspersecond; - return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromDecilitersPerDay(double decilitersperday) - { - double value = (double) decilitersperday; - return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromDecilitersPerHour(double decilitersperhour) - { - double value = (double) decilitersperhour; - return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromDecilitersPerMinute(double decilitersperminute) - { - double value = (double) decilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromDecilitersPerSecond(double deciliterspersecond) - { - double value = (double) deciliterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilolitersPerDay(double kilolitersperday) - { - double value = (double) kilolitersperday; - return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilolitersPerHour(double kilolitersperhour) - { - double value = (double) kilolitersperhour; - return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilolitersPerMinute(double kilolitersperminute) - { - double value = (double) kilolitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilolitersPerSecond(double kiloliterspersecond) - { - double value = (double) kiloliterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromKilousGallonsPerMinute(double kilousgallonsperminute) - { - double value = (double) kilousgallonsperminute; - return new VolumeFlow(value, VolumeFlowUnit.KilousGallonPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerDay(double litersperday) - { - double value = (double) litersperday; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerHour(double litersperhour) - { - double value = (double) litersperhour; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerMinute(double litersperminute) - { - double value = (double) litersperminute; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromLitersPerSecond(double literspersecond) - { - double value = (double) literspersecond; - return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMegalitersPerDay(double megalitersperday) - { - double value = (double) megalitersperday; - return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMegaukGallonsPerSecond(double megaukgallonspersecond) - { - double value = (double) megaukgallonspersecond; - return new VolumeFlow(value, VolumeFlowUnit.MegaukGallonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMicrolitersPerDay(double microlitersperday) - { - double value = (double) microlitersperday; - return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMicrolitersPerHour(double microlitersperhour) - { - double value = (double) microlitersperhour; - return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMicrolitersPerMinute(double microlitersperminute) - { - double value = (double) microlitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMicrolitersPerSecond(double microliterspersecond) - { - double value = (double) microliterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillilitersPerDay(double millilitersperday) - { - double value = (double) millilitersperday; - return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillilitersPerHour(double millilitersperhour) - { - double value = (double) millilitersperhour; - return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillilitersPerMinute(double millilitersperminute) - { - double value = (double) millilitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillilitersPerSecond(double milliliterspersecond) - { - double value = (double) milliliterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) - { - double value = (double) millionusgallonsperday; - return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromNanolitersPerDay(double nanolitersperday) - { - double value = (double) nanolitersperday; - return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromNanolitersPerHour(double nanolitersperhour) - { - double value = (double) nanolitersperhour; - return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromNanolitersPerMinute(double nanolitersperminute) - { - double value = (double) nanolitersperminute; - return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromNanolitersPerSecond(double nanoliterspersecond) - { - double value = (double) nanoliterspersecond; - return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerDay(double oilbarrelsperday) - { - double value = (double) oilbarrelsperday; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerHour(double oilbarrelsperhour) - { - double value = (double) oilbarrelsperhour; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerMinute(double oilbarrelsperminute) - { - double value = (double) oilbarrelsperminute; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromOilBarrelsPerSecond(double oilbarrelspersecond) - { - double value = (double) oilbarrelspersecond; - return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUkGallonsPerDay(double ukgallonsperday) - { - double value = (double) ukgallonsperday; - return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUkGallonsPerHour(double ukgallonsperhour) - { - double value = (double) ukgallonsperhour; - return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUkGallonsPerMinute(double ukgallonsperminute) - { - double value = (double) ukgallonsperminute; - return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUkGallonsPerSecond(double ukgallonspersecond) - { - double value = (double) ukgallonspersecond; - return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerSecond); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerDay(double usgallonsperday) - { - double value = (double) usgallonsperday; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerDay); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerHour(double usgallonsperhour) - { - double value = (double) usgallonsperhour; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerMinute(double usgallonsperminute) - { - double value = (double) usgallonsperminute; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlow FromUsGallonsPerSecond(double usgallonspersecond) - { - double value = (double) usgallonspersecond; - return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumeFlow unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) - { - return new VolumeFlow((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumeFlow Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeFlow Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumeFlow result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out VolumeFlow result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeFlowUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VolumeFlowUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VolumeFlowUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumeFlow objVolumeFlow)) throw new ArgumentException("Expected type VolumeFlow.", nameof(obj)); - - return CompareTo(objVolumeFlow); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(VolumeFlow other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumeFlow objVolumeFlow)) - return false; - - return Equals(objVolumeFlow); - } - - public bool Equals(VolumeFlow other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VolumeFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VolumeFlowUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumeFlow to another VolumeFlow with the unit representation . - /// - /// A VolumeFlow with the specified unit. - public VolumeFlow ToUnit(VolumeFlowUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumeFlow(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumeFlowUnit.AcreFootPerDay: return _value / 70.0457; - case VolumeFlowUnit.AcreFootPerHour: return _value / 2.91857; - case VolumeFlowUnit.AcreFootPerMinute: return _value / 0.0486427916; - case VolumeFlowUnit.AcreFootPerSecond: return _value / 0.000810713194; - case VolumeFlowUnit.CentiliterPerDay: return (_value / 86400000) * 1e-2d; - case VolumeFlowUnit.CentiliterPerHour: return (_value / 3600000.000) * 1e-2d; - case VolumeFlowUnit.CentiliterPerMinute: return (_value / 60000.00000) * 1e-2d; - case VolumeFlowUnit.CentiliterPerSecond: return (_value / 1000) * 1e-2d; - case VolumeFlowUnit.CubicCentimeterPerMinute: return _value * 1.6666666666667e-8; - case VolumeFlowUnit.CubicDecimeterPerMinute: return _value / 60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return _value * 7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return _value / 2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return _value / 35.314666721; - case VolumeFlowUnit.CubicMeterPerDay: return _value / 86400; - case VolumeFlowUnit.CubicMeterPerHour: return _value / 3600; - case VolumeFlowUnit.CubicMeterPerMinute: return _value / 60; - case VolumeFlowUnit.CubicMeterPerSecond: return _value; - case VolumeFlowUnit.CubicMillimeterPerSecond: return _value * 1e-9; - case VolumeFlowUnit.CubicYardPerDay: return _value / 113007; - case VolumeFlowUnit.CubicYardPerHour: return _value * 2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return _value * 0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return _value * 0.764554857984; - case VolumeFlowUnit.DeciliterPerDay: return (_value / 86400000) * 1e-1d; - case VolumeFlowUnit.DeciliterPerHour: return (_value / 3600000.000) * 1e-1d; - case VolumeFlowUnit.DeciliterPerMinute: return (_value / 60000.00000) * 1e-1d; - case VolumeFlowUnit.DeciliterPerSecond: return (_value / 1000) * 1e-1d; - case VolumeFlowUnit.KiloliterPerDay: return (_value / 86400000) * 1e3d; - case VolumeFlowUnit.KiloliterPerHour: return (_value / 3600000.000) * 1e3d; - case VolumeFlowUnit.KiloliterPerMinute: return (_value / 60000.00000) * 1e3d; - case VolumeFlowUnit.KiloliterPerSecond: return (_value / 1000) * 1e3d; - case VolumeFlowUnit.KilousGallonPerMinute: return _value / 15.850323141489; - case VolumeFlowUnit.LiterPerDay: return _value / 86400000; - case VolumeFlowUnit.LiterPerHour: return _value / 3600000.000; - case VolumeFlowUnit.LiterPerMinute: return _value / 60000.00000; - case VolumeFlowUnit.LiterPerSecond: return _value / 1000; - case VolumeFlowUnit.MegaliterPerDay: return (_value / 86400000) * 1e6d; - case VolumeFlowUnit.MegaukGallonPerSecond: return (_value / 219.969) * 1e6d; - case VolumeFlowUnit.MicroliterPerDay: return (_value / 86400000) * 1e-6d; - case VolumeFlowUnit.MicroliterPerHour: return (_value / 3600000.000) * 1e-6d; - case VolumeFlowUnit.MicroliterPerMinute: return (_value / 60000.00000) * 1e-6d; - case VolumeFlowUnit.MicroliterPerSecond: return (_value / 1000) * 1e-6d; - case VolumeFlowUnit.MilliliterPerDay: return (_value / 86400000) * 1e-3d; - case VolumeFlowUnit.MilliliterPerHour: return (_value / 3600000.000) * 1e-3d; - case VolumeFlowUnit.MilliliterPerMinute: return (_value / 60000.00000) * 1e-3d; - case VolumeFlowUnit.MilliliterPerSecond: return (_value / 1000) * 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return _value / 22.824465227; - case VolumeFlowUnit.NanoliterPerDay: return (_value / 86400000) * 1e-9d; - case VolumeFlowUnit.NanoliterPerHour: return (_value / 3600000.000) * 1e-9d; - case VolumeFlowUnit.NanoliterPerMinute: return (_value / 60000.00000) * 1e-9d; - case VolumeFlowUnit.NanoliterPerSecond: return (_value / 1000) * 1e-9d; - case VolumeFlowUnit.OilBarrelPerDay: return _value * 1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelPerHour: return _value * 4.41631375e-5; - case VolumeFlowUnit.OilBarrelPerMinute: return _value * 2.64978825e-3; - case VolumeFlowUnit.OilBarrelPerSecond: return _value / 6.28981; - case VolumeFlowUnit.UkGallonPerDay: return _value / 19005304; - case VolumeFlowUnit.UkGallonPerHour: return _value / 791887.667; - case VolumeFlowUnit.UkGallonPerMinute: return _value / 13198.2; - case VolumeFlowUnit.UkGallonPerSecond: return _value / 219.969; - case VolumeFlowUnit.UsGallonPerDay: return _value / 22824465.227; - case VolumeFlowUnit.UsGallonPerHour: return _value / 951019.38848933424; - case VolumeFlowUnit.UsGallonPerMinute: return _value / 15850.323141489; - case VolumeFlowUnit.UsGallonPerSecond: return _value / 264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeFlowUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeFlowUnit.AcreFootPerDay: return baseUnitValue * 70.0457; - case VolumeFlowUnit.AcreFootPerHour: return baseUnitValue * 2.91857; - case VolumeFlowUnit.AcreFootPerMinute: return baseUnitValue * 0.0486427916; - case VolumeFlowUnit.AcreFootPerSecond: return baseUnitValue * 0.000810713194; - case VolumeFlowUnit.CentiliterPerDay: return (baseUnitValue * 86400000) / 1e-2d; - case VolumeFlowUnit.CentiliterPerHour: return (baseUnitValue * 3600000.000) / 1e-2d; - case VolumeFlowUnit.CentiliterPerMinute: return (baseUnitValue * 60000.00000) / 1e-2d; - case VolumeFlowUnit.CentiliterPerSecond: return (baseUnitValue * 1000) / 1e-2d; - case VolumeFlowUnit.CubicCentimeterPerMinute: return baseUnitValue / 1.6666666666667e-8; - case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue * 60000.00000; - case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue / 7.8657907199999087346816086183876e-6; - case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue * 2118.88000326; - case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue * 35.314666721; - case VolumeFlowUnit.CubicMeterPerDay: return baseUnitValue * 86400; - case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue * 3600; - case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue * 60; - case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; - case VolumeFlowUnit.CubicMillimeterPerSecond: return baseUnitValue / 1e-9; - case VolumeFlowUnit.CubicYardPerDay: return baseUnitValue * 113007; - case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue / 2.1237634944E-4; - case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue / 0.0127425809664; - case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue / 0.764554857984; - case VolumeFlowUnit.DeciliterPerDay: return (baseUnitValue * 86400000) / 1e-1d; - case VolumeFlowUnit.DeciliterPerHour: return (baseUnitValue * 3600000.000) / 1e-1d; - case VolumeFlowUnit.DeciliterPerMinute: return (baseUnitValue * 60000.00000) / 1e-1d; - case VolumeFlowUnit.DeciliterPerSecond: return (baseUnitValue * 1000) / 1e-1d; - case VolumeFlowUnit.KiloliterPerDay: return (baseUnitValue * 86400000) / 1e3d; - case VolumeFlowUnit.KiloliterPerHour: return (baseUnitValue * 3600000.000) / 1e3d; - case VolumeFlowUnit.KiloliterPerMinute: return (baseUnitValue * 60000.00000) / 1e3d; - case VolumeFlowUnit.KiloliterPerSecond: return (baseUnitValue * 1000) / 1e3d; - case VolumeFlowUnit.KilousGallonPerMinute: return baseUnitValue * 15.850323141489; - case VolumeFlowUnit.LiterPerDay: return baseUnitValue * 86400000; - case VolumeFlowUnit.LiterPerHour: return baseUnitValue * 3600000.000; - case VolumeFlowUnit.LiterPerMinute: return baseUnitValue * 60000.00000; - case VolumeFlowUnit.LiterPerSecond: return baseUnitValue * 1000; - case VolumeFlowUnit.MegaliterPerDay: return (baseUnitValue * 86400000) / 1e6d; - case VolumeFlowUnit.MegaukGallonPerSecond: return (baseUnitValue * 219.969) / 1e6d; - case VolumeFlowUnit.MicroliterPerDay: return (baseUnitValue * 86400000) / 1e-6d; - case VolumeFlowUnit.MicroliterPerHour: return (baseUnitValue * 3600000.000) / 1e-6d; - case VolumeFlowUnit.MicroliterPerMinute: return (baseUnitValue * 60000.00000) / 1e-6d; - case VolumeFlowUnit.MicroliterPerSecond: return (baseUnitValue * 1000) / 1e-6d; - case VolumeFlowUnit.MilliliterPerDay: return (baseUnitValue * 86400000) / 1e-3d; - case VolumeFlowUnit.MilliliterPerHour: return (baseUnitValue * 3600000.000) / 1e-3d; - case VolumeFlowUnit.MilliliterPerMinute: return (baseUnitValue * 60000.00000) / 1e-3d; - case VolumeFlowUnit.MilliliterPerSecond: return (baseUnitValue * 1000) / 1e-3d; - case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue * 22.824465227; - case VolumeFlowUnit.NanoliterPerDay: return (baseUnitValue * 86400000) / 1e-9d; - case VolumeFlowUnit.NanoliterPerHour: return (baseUnitValue * 3600000.000) / 1e-9d; - case VolumeFlowUnit.NanoliterPerMinute: return (baseUnitValue * 60000.00000) / 1e-9d; - case VolumeFlowUnit.NanoliterPerSecond: return (baseUnitValue * 1000) / 1e-9d; - case VolumeFlowUnit.OilBarrelPerDay: return baseUnitValue / 1.8401307283333333333333333333333e-6; - case VolumeFlowUnit.OilBarrelPerHour: return baseUnitValue / 4.41631375e-5; - case VolumeFlowUnit.OilBarrelPerMinute: return baseUnitValue / 2.64978825e-3; - case VolumeFlowUnit.OilBarrelPerSecond: return baseUnitValue * 6.28981; - case VolumeFlowUnit.UkGallonPerDay: return baseUnitValue * 19005304; - case VolumeFlowUnit.UkGallonPerHour: return baseUnitValue * 791887.667; - case VolumeFlowUnit.UkGallonPerMinute: return baseUnitValue * 13198.2; - case VolumeFlowUnit.UkGallonPerSecond: return baseUnitValue * 219.969; - case VolumeFlowUnit.UsGallonPerDay: return baseUnitValue * 22824465.227; - case VolumeFlowUnit.UsGallonPerHour: return baseUnitValue * 951019.38848933424; - case VolumeFlowUnit.UsGallonPerMinute: return baseUnitValue * 15850.323141489; - case VolumeFlowUnit.UsGallonPerSecond: return baseUnitValue * 264.1720523581484; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs deleted file mode 100644 index 61e97344ce..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ /dev/null @@ -1,612 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// The volumetric flow rate per area is the volume of fluid which passes through a given unit surface area per unit time. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VolumeFlowPerArea : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumeFlowPerAreaUnit? _unit; - - static VolumeFlowPerArea() - { - BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); - BaseUnit = VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter; - MaxValue = new VolumeFlowPerArea(double.MaxValue, BaseUnit); - MinValue = new VolumeFlowPerArea(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumeFlowPerArea; - Units = Enum.GetValues(typeof(VolumeFlowPerAreaUnit)).Cast().Except(new VolumeFlowPerAreaUnit[]{ VolumeFlowPerAreaUnit.Undefined }).ToArray(); - Zero = new VolumeFlowPerArea(0, BaseUnit); - Info = new QuantityInfo(QuantityType.VolumeFlowPerArea, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CubicMeterPerSecondPerSquareMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public VolumeFlowPerArea() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private VolumeFlowPerArea(double value, VolumeFlowPerAreaUnit unit) - { - if (unit == VolumeFlowPerAreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of VolumeFlowPerArea, which is CubicMeterPerSecondPerSquareMeter. All conversions go via this value. - /// - public static VolumeFlowPerAreaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of VolumeFlowPerArea - /// - public static VolumeFlowPerArea MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumeFlowPerArea - /// - public static VolumeFlowPerArea MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the VolumeFlowPerArea quantity. - /// - public static VolumeFlowPerAreaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecondPerSquareMeter. - /// - public static VolumeFlowPerArea Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumeFlowPerAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => VolumeFlowPerArea.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumeFlowPerArea.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CubicFeetPerMinutePerSquareFoot => As(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerSecondPerSquareMeter => As(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); - - #endregion - - #region Static Methods - - 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²)"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VolumeFlowPerAreaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VolumeFlowPerAreaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(double cubicfeetperminutepersquarefoot) - { - double value = (double) cubicfeetperminutepersquarefoot; - return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(double cubicmeterspersecondpersquaremeter) - { - double value = (double) cubicmeterspersecondpersquaremeter; - return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumeFlowPerArea unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumeFlowPerArea From(double value, VolumeFlowPerAreaUnit fromUnit) - { - return new VolumeFlowPerArea((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumeFlowPerArea Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeFlowPerArea Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumeFlowPerArea result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out VolumeFlowPerArea result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumeFlowPerAreaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumeFlowPerAreaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VolumeFlowPerAreaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VolumeFlowPerAreaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumeFlowPerArea objVolumeFlowPerArea)) throw new ArgumentException("Expected type VolumeFlowPerArea.", nameof(obj)); - - return CompareTo(objVolumeFlowPerArea); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(VolumeFlowPerArea other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumeFlowPerArea objVolumeFlowPerArea)) - return false; - - return Equals(objVolumeFlowPerArea); - } - - public bool Equals(VolumeFlowPerArea other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VolumeFlowPerArea within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeFlowPerArea. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VolumeFlowPerAreaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowPerAreaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumeFlowPerArea to another VolumeFlowPerArea with the unit representation . - /// - /// A VolumeFlowPerArea with the specified unit. - public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumeFlowPerArea(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot: return _value / 196.850394; - case VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter: return _value; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumeFlowPerAreaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot: return baseUnitValue * 196.850394; - case VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter: return baseUnitValue; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumePerLength.g.cs deleted file mode 100644 index f76e626b89..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumePerLength.g.cs +++ /dev/null @@ -1,707 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// Volume, typically of fluid, that a container can hold within a unit of length. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VolumePerLength : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumePerLengthUnit? _unit; - - static VolumePerLength() - { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - BaseUnit = VolumePerLengthUnit.CubicMeterPerMeter; - MaxValue = new VolumePerLength(double.MaxValue, BaseUnit); - MinValue = new VolumePerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumePerLength; - Units = Enum.GetValues(typeof(VolumePerLengthUnit)).Cast().Except(new VolumePerLengthUnit[]{ VolumePerLengthUnit.Undefined }).ToArray(); - Zero = new VolumePerLength(0, BaseUnit); - Info = new QuantityInfo(QuantityType.VolumePerLength, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit CubicMeterPerMeter. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public VolumePerLength() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private VolumePerLength(double value, VolumePerLengthUnit unit) - { - if (unit == VolumePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of VolumePerLength, which is CubicMeterPerMeter. All conversions go via this value. - /// - public static VolumePerLengthUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of VolumePerLength - /// - public static VolumePerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumePerLength - /// - public static VolumePerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the VolumePerLength quantity. - /// - public static VolumePerLengthUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerMeter. - /// - public static VolumePerLength Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => VolumePerLength.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumePerLength.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CubicMetersPerMeter => As(VolumePerLengthUnit.CubicMeterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYardsPerFoot => As(VolumePerLengthUnit.CubicYardPerFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double CubicYardsPerUsSurveyFoot => As(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerKilometer => As(VolumePerLengthUnit.LiterPerKilometer); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerMeter => As(VolumePerLengthUnit.LiterPerMeter); - - /// - /// Gets a value of this quantity converted into - /// - public double LitersPerMillimeter => As(VolumePerLengthUnit.LiterPerMillimeter); - - /// - /// Gets a value of this quantity converted into - /// - public double OilBarrelsPerFoot => As(VolumePerLengthUnit.OilBarrelPerFoot); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VolumePerLengthUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VolumePerLengthUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromCubicMetersPerMeter(double cubicmeterspermeter) - { - double value = (double) cubicmeterspermeter; - return new VolumePerLength(value, VolumePerLengthUnit.CubicMeterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromCubicYardsPerFoot(double cubicyardsperfoot) - { - double value = (double) cubicyardsperfoot; - return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromCubicYardsPerUsSurveyFoot(double cubicyardsperussurveyfoot) - { - double value = (double) cubicyardsperussurveyfoot; - return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerUsSurveyFoot); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromLitersPerKilometer(double litersperkilometer) - { - double value = (double) litersperkilometer; - return new VolumePerLength(value, VolumePerLengthUnit.LiterPerKilometer); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromLitersPerMeter(double literspermeter) - { - double value = (double) literspermeter; - return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromLitersPerMillimeter(double literspermillimeter) - { - double value = (double) literspermillimeter; - return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMillimeter); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumePerLength FromOilBarrelsPerFoot(double oilbarrelsperfoot) - { - double value = (double) oilbarrelsperfoot; - return new VolumePerLength(value, VolumePerLengthUnit.OilBarrelPerFoot); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumePerLength unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumePerLength From(double value, VolumePerLengthUnit fromUnit) - { - return new VolumePerLength((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumePerLength Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumePerLength Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumePerLength result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out VolumePerLength result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumePerLengthUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VolumePerLengthUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VolumePerLengthUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumePerLength objVolumePerLength)) throw new ArgumentException("Expected type VolumePerLength.", nameof(obj)); - - return CompareTo(objVolumePerLength); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(VolumePerLength other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumePerLength objVolumePerLength)) - return false; - - return Equals(objVolumePerLength); - } - - public bool Equals(VolumePerLength other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VolumePerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumePerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VolumePerLengthUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumePerLengthUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumePerLength to another VolumePerLength with the unit representation . - /// - /// A VolumePerLength with the specified unit. - public VolumePerLength ToUnit(VolumePerLengthUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumePerLength(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumePerLengthUnit.CubicMeterPerMeter: return _value; - case VolumePerLengthUnit.CubicYardPerFoot: return _value * 2.50838208; - case VolumePerLengthUnit.CubicYardPerUsSurveyFoot: return _value * 2.50837706323584; - case VolumePerLengthUnit.LiterPerKilometer: return _value / 1e6; - case VolumePerLengthUnit.LiterPerMeter: return _value / 1000; - case VolumePerLengthUnit.LiterPerMillimeter: return _value; - case VolumePerLengthUnit.OilBarrelPerFoot: return _value / 1.91713408; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumePerLengthUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumePerLengthUnit.CubicMeterPerMeter: return baseUnitValue; - case VolumePerLengthUnit.CubicYardPerFoot: return baseUnitValue / 2.50838208; - case VolumePerLengthUnit.CubicYardPerUsSurveyFoot: return baseUnitValue / 2.50837706323584; - case VolumePerLengthUnit.LiterPerKilometer: return baseUnitValue * 1e6; - case VolumePerLengthUnit.LiterPerMeter: return baseUnitValue * 1000; - case VolumePerLengthUnit.LiterPerMillimeter: return baseUnitValue; - case VolumePerLengthUnit.OilBarrelPerFoot: return baseUnitValue * 1.91713408; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs deleted file mode 100644 index df8122ba81..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ /dev/null @@ -1,748 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// 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. - /// - /// - /// https://en.wikipedia.org/wiki/Volumetric_heat_capacity - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class VolumetricHeatCapacity : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly VolumetricHeatCapacityUnit? _unit; - - static VolumetricHeatCapacity() - { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, -1, 0, 0); - BaseUnit = VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin; - MaxValue = new VolumetricHeatCapacity(double.MaxValue, BaseUnit); - MinValue = new VolumetricHeatCapacity(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumetricHeatCapacity; - Units = Enum.GetValues(typeof(VolumetricHeatCapacityUnit)).Cast().Except(new VolumetricHeatCapacityUnit[]{ VolumetricHeatCapacityUnit.Undefined }).ToArray(); - Zero = new VolumetricHeatCapacity(0, BaseUnit); - Info = new QuantityInfo(QuantityType.VolumetricHeatCapacity, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit JoulePerCubicMeterKelvin. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public VolumetricHeatCapacity() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private VolumetricHeatCapacity(double value, VolumetricHeatCapacityUnit unit) - { - if (unit == VolumetricHeatCapacityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of VolumetricHeatCapacity, which is JoulePerCubicMeterKelvin. All conversions go via this value. - /// - public static VolumetricHeatCapacityUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of VolumetricHeatCapacity - /// - public static VolumetricHeatCapacity MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumetricHeatCapacity - /// - public static VolumetricHeatCapacity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the VolumetricHeatCapacity quantity. - /// - public static VolumetricHeatCapacityUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerCubicMeterKelvin. - /// - public static VolumetricHeatCapacity Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public VolumetricHeatCapacityUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => VolumetricHeatCapacity.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => VolumetricHeatCapacity.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double BtusPerCubicFootDegreeFahrenheit => As(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); - - /// - /// Gets a value of this quantity converted into - /// - public double CaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double JoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double KilocaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double KilojoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); - - /// - /// Gets a value of this quantity converted into - /// - public double MegajoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(VolumetricHeatCapacityUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(VolumetricHeatCapacityUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(double btuspercubicfootdegreefahrenheit) - { - double value = (double) btuspercubicfootdegreefahrenheit; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius(double caloriespercubiccentimeterdegreecelsius) - { - double value = (double) caloriespercubiccentimeterdegreecelsius; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(double joulespercubicmeterdegreecelsius) - { - double value = (double) joulespercubicmeterdegreecelsius; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(double joulespercubicmeterkelvin) - { - double value = (double) joulespercubicmeterkelvin; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCelsius(double kilocaloriespercubiccentimeterdegreecelsius) - { - double value = (double) kilocaloriespercubiccentimeterdegreecelsius; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(double kilojoulespercubicmeterdegreecelsius) - { - double value = (double) kilojoulespercubicmeterdegreecelsius; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(double kilojoulespercubicmeterkelvin) - { - double value = (double) kilojoulespercubicmeterkelvin; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(double megajoulespercubicmeterdegreecelsius) - { - double value = (double) megajoulespercubicmeterdegreecelsius; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(double megajoulespercubicmeterkelvin) - { - double value = (double) megajoulespercubicmeterkelvin; - return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// VolumetricHeatCapacity unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static VolumetricHeatCapacity From(double value, VolumetricHeatCapacityUnit fromUnit) - { - return new VolumetricHeatCapacity((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static VolumetricHeatCapacity Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumetricHeatCapacity Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out VolumetricHeatCapacity result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out VolumetricHeatCapacity result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static VolumetricHeatCapacityUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static VolumetricHeatCapacityUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out VolumetricHeatCapacityUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out VolumetricHeatCapacityUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumetricHeatCapacity objVolumetricHeatCapacity)) throw new ArgumentException("Expected type VolumetricHeatCapacity.", nameof(obj)); - - return CompareTo(objVolumetricHeatCapacity); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(VolumetricHeatCapacity other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumetricHeatCapacity objVolumetricHeatCapacity)) - return false; - - return Equals(objVolumetricHeatCapacity); - } - - public bool Equals(VolumetricHeatCapacity other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another VolumetricHeatCapacity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumetricHeatCapacity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((VolumetricHeatCapacityUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumetricHeatCapacityUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this VolumetricHeatCapacity to another VolumetricHeatCapacity with the unit representation . - /// - /// A VolumetricHeatCapacity with the specified unit. - public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new VolumetricHeatCapacity(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit: return _value / 1.4910660e-5; - case VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius: return _value / 2.388459e-7; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius: return _value; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin: return _value; - case VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius: return (_value / 2.388459e-7) * 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius: return (_value) * 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin: return (_value) * 1e3d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius: return (_value) * 1e6d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin: return (_value) * 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(VolumetricHeatCapacityUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit: return baseUnitValue * 1.4910660e-5; - case VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius: return baseUnitValue * 2.388459e-7; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius: return baseUnitValue; - case VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin: return baseUnitValue; - case VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius: return (baseUnitValue * 2.388459e-7) / 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius: return (baseUnitValue) / 1e3d; - case VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin: return (baseUnitValue) / 1e3d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius: return (baseUnitValue) / 1e6d; - case VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin: return (baseUnitValue) / 1e6d; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs deleted file mode 100644 index e55fb757c9..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ /dev/null @@ -1,688 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Globalization; -using System.Linq; -using JetBrains.Annotations; -using UnitsNet.Units; -using UnitsNet.InternalHelpers; - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// A geometric property of an area that is used to determine the warping stress. - /// - // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components - // Public structures can't have any members other than public fields, and those fields must be value types or strings. - // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. - public sealed partial class WarpingMomentOfInertia : IQuantity - { - /// - /// The numeric value this quantity was constructed with. - /// - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - private readonly WarpingMomentOfInertiaUnit? _unit; - - static WarpingMomentOfInertia() - { - BaseDimensions = new BaseDimensions(6, 0, 0, 0, 0, 0, 0); - BaseUnit = WarpingMomentOfInertiaUnit.MeterToTheSixth; - MaxValue = new WarpingMomentOfInertia(double.MaxValue, BaseUnit); - MinValue = new WarpingMomentOfInertia(double.MinValue, BaseUnit); - QuantityType = QuantityType.WarpingMomentOfInertia; - Units = Enum.GetValues(typeof(WarpingMomentOfInertiaUnit)).Cast().Except(new WarpingMomentOfInertiaUnit[]{ WarpingMomentOfInertiaUnit.Undefined }).ToArray(); - Zero = new WarpingMomentOfInertia(0, BaseUnit); - Info = new QuantityInfo(QuantityType.WarpingMomentOfInertia, Units.Cast().ToArray(), BaseUnit, Zero, BaseDimensions); - } - - /// - /// Creates the quantity with a value of 0 in the base unit MeterToTheSixth. - /// - /// - /// Windows Runtime Component requires a default constructor. - /// - public WarpingMomentOfInertia() - { - _value = 0; - _unit = BaseUnit; - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. - /// If value is NaN or Infinity. - private WarpingMomentOfInertia(double value, WarpingMomentOfInertiaUnit unit) - { - if (unit == WarpingMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - - _value = Guard.EnsureValidNumber(value, nameof(value)); - _unit = unit; - } - - #region Static Properties - - /// - /// Information about the quantity type, such as unit values and names. - /// - internal static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions { get; } - - /// - /// The base unit of WarpingMomentOfInertia, which is MeterToTheSixth. All conversions go via this value. - /// - public static WarpingMomentOfInertiaUnit BaseUnit { get; } - - /// - /// Represents the largest possible value of WarpingMomentOfInertia - /// - public static WarpingMomentOfInertia MaxValue { get; } - - /// - /// Represents the smallest possible value of WarpingMomentOfInertia - /// - public static WarpingMomentOfInertia MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - - /// - /// All units of measurement for the WarpingMomentOfInertia quantity. - /// - public static WarpingMomentOfInertiaUnit[] Units { get; } - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheSixth. - /// - public static WarpingMomentOfInertia Zero { get; } - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => Convert.ToDouble(_value); - - /// - object IQuantity.Unit => Unit; - - /// - /// The unit this quantity was constructed with -or- if default ctor was used. - /// - public WarpingMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - internal QuantityInfo QuantityInfo => Info; - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => WarpingMomentOfInertia.QuantityType; - - /// - /// The of this quantity. - /// - public BaseDimensions Dimensions => WarpingMomentOfInertia.BaseDimensions; - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double CentimetersToTheSixth => As(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); - - /// - /// Gets a value of this quantity converted into - /// - public double DecimetersToTheSixth => As(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); - - /// - /// Gets a value of this quantity converted into - /// - public double FeetToTheSixth => As(WarpingMomentOfInertiaUnit.FootToTheSixth); - - /// - /// Gets a value of this quantity converted into - /// - public double InchesToTheSixth => As(WarpingMomentOfInertiaUnit.InchToTheSixth); - - /// - /// Gets a value of this quantity converted into - /// - public double MetersToTheSixth => As(WarpingMomentOfInertiaUnit.MeterToTheSixth); - - /// - /// Gets a value of this quantity converted into - /// - public double MillimetersToTheSixth => As(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); - - #endregion - - #region Static Methods - - 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"}); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static WarpingMomentOfInertia FromCentimetersToTheSixth(double centimeterstothesixth) - { - double value = (double) centimeterstothesixth; - return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.CentimeterToTheSixth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static WarpingMomentOfInertia FromDecimetersToTheSixth(double decimeterstothesixth) - { - double value = (double) decimeterstothesixth; - return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.DecimeterToTheSixth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static WarpingMomentOfInertia FromFeetToTheSixth(double feettothesixth) - { - double value = (double) feettothesixth; - return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.FootToTheSixth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static WarpingMomentOfInertia FromInchesToTheSixth(double inchestothesixth) - { - double value = (double) inchestothesixth; - return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.InchToTheSixth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static WarpingMomentOfInertia FromMetersToTheSixth(double meterstothesixth) - { - double value = (double) meterstothesixth; - return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MeterToTheSixth); - } - - /// - /// Creates a from . - /// - /// If value is NaN or Infinity. - [Windows.Foundation.Metadata.DefaultOverload] - public static WarpingMomentOfInertia FromMillimetersToTheSixth(double millimeterstothesixth) - { - double value = (double) millimeterstothesixth; - return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MillimeterToTheSixth); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// WarpingMomentOfInertia unit value. - // Fix name conflict with parameter "value" - [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] - public static WarpingMomentOfInertia From(double value, WarpingMomentOfInertiaUnit fromUnit) - { - return new WarpingMomentOfInertia((double)value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static WarpingMomentOfInertia Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static WarpingMomentOfInertia Parse(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - public static bool TryParse([CanBeNull] string str, out WarpingMomentOfInertia result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out WarpingMomentOfInertia result) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return QuantityParser.Default.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static WarpingMomentOfInertiaUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", new CultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static WarpingMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.Parse(str, provider); - } - - public static bool TryParseUnit(string str, out WarpingMomentOfInertiaUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", new CultureInfo("en-US")); - /// - /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out WarpingMomentOfInertiaUnit unit) - { - IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); - return UnitParser.Default.TryParse(str, provider, out unit); - } - - #endregion - - #region Equality / IComparable - - public int CompareTo(object obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is WarpingMomentOfInertia objWarpingMomentOfInertia)) throw new ArgumentException("Expected type WarpingMomentOfInertia.", nameof(obj)); - - return CompareTo(objWarpingMomentOfInertia); - } - - // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods - internal int CompareTo(WarpingMomentOfInertia other) - { - return _value.CompareTo(other.AsBaseNumericType(this.Unit)); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public override bool Equals(object obj) - { - if (obj is null || !(obj is WarpingMomentOfInertia objWarpingMomentOfInertia)) - return false; - - return Equals(objWarpingMomentOfInertia); - } - - public bool Equals(WarpingMomentOfInertia other) - { - return _value.Equals(other.AsBaseNumericType(this.Unit)); - } - - /// - /// - /// Compare equality to another WarpingMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating point operations and using System.Double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - 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 = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); - - return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current WarpingMomentOfInertia. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); - } - - #endregion - - #region Conversion Methods - - double IQuantity.As(object unit) => As((WarpingMomentOfInertiaUnit)unit); - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(WarpingMomentOfInertiaUnit unit) - { - if (Unit == unit) - return Convert.ToDouble(Value); - - var converted = AsBaseNumericType(unit); - return Convert.ToDouble(converted); - } - - /// - /// Converts this WarpingMomentOfInertia to another WarpingMomentOfInertia with the unit representation . - /// - /// A WarpingMomentOfInertia with the specified unit. - public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit) - { - var convertedValue = AsBaseNumericType(unit); - return new WarpingMomentOfInertia(convertedValue, unit); - } - - /// - /// Converts the current value + unit to the base unit. - /// This is typically the first step in converting from one unit to another. - /// - /// The value in the base unit representation. - private double AsBaseUnit() - { - switch(Unit) - { - case WarpingMomentOfInertiaUnit.CentimeterToTheSixth: return _value / 1e12; - case WarpingMomentOfInertiaUnit.DecimeterToTheSixth: return _value / 1e6; - case WarpingMomentOfInertiaUnit.FootToTheSixth: return _value * Math.Pow(0.3048, 6); - case WarpingMomentOfInertiaUnit.InchToTheSixth: return _value * Math.Pow(2.54e-2, 6); - case WarpingMomentOfInertiaUnit.MeterToTheSixth: return _value; - case WarpingMomentOfInertiaUnit.MillimeterToTheSixth: return _value / 1e18; - default: - throw new NotImplementedException($"Can not convert {Unit} to base units."); - } - } - - private double AsBaseNumericType(WarpingMomentOfInertiaUnit unit) - { - if (Unit == unit) - return _value; - - var baseUnitValue = AsBaseUnit(); - - switch(unit) - { - case WarpingMomentOfInertiaUnit.CentimeterToTheSixth: return baseUnitValue * 1e12; - case WarpingMomentOfInertiaUnit.DecimeterToTheSixth: return baseUnitValue * 1e6; - case WarpingMomentOfInertiaUnit.FootToTheSixth: return baseUnitValue / Math.Pow(0.3048, 6); - case WarpingMomentOfInertiaUnit.InchToTheSixth: return baseUnitValue / Math.Pow(2.54e-2, 6); - case WarpingMomentOfInertiaUnit.MeterToTheSixth: return baseUnitValue; - case WarpingMomentOfInertiaUnit.MillimeterToTheSixth: return baseUnitValue * 1e18; - default: - throw new NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } - - #endregion - - #region ToString Methods - - /// - /// Get default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null); - } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName) - { - var provider = cultureName; - return ToString(provider, 2); - } - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString(string cultureName, int significantDigitsAfterRadix) - { - var provider = cultureName; - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { - var provider = GetFormatProviderFromCultureName(cultureName); - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? GlobalConfiguration.DefaultCulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - - #endregion - - private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { - return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs deleted file mode 100644 index d4444d39c3..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantity.g.cs +++ /dev/null @@ -1,921 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using System.Collections.Generic; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// Dynamically parse or construct quantities when types are only known at runtime. - /// - internal static partial class Quantity - { - /// - /// Try to dynamically construct a quantity. - /// - /// Numeric value. - /// Unit enum value. - /// The resulting quantity if successful, otherwise default. - /// True if successful with assigned the value, otherwise false. - internal static bool TryFrom(double value, Enum unit, 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 LapseRateUnit lapseRateUnit: - quantity = LapseRate.From(value, lapseRateUnit); - 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; - } - } - } - - /// - internal static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); - - /// - /// Dynamically parse a quantity string representation. - /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. - /// The parsed quantity. - /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. - internal static IQuantity Parse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString) - { - if (!typeof(IQuantity).Wrap().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}."); - } - - /// - internal static bool TryParse(Type quantityType, string quantityString, out IQuantity quantity) => - TryParse(null, quantityType, quantityString, out quantity); - - /// - /// Try to dynamically parse a quantity string representation. - /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. - /// The resulting quantity if successful, otherwise default. - /// The parsed quantity. - internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString, out IQuantity quantity) - { - quantity = default(IQuantity); - - if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) - return false; - - var parser = QuantityParser.Default; - - if (quantityType == typeof(Acceleration)) - return parser.TryParse(quantityString, formatProvider, Acceleration.From, out quantity); - - if (quantityType == typeof(AmountOfSubstance)) - return parser.TryParse(quantityString, formatProvider, AmountOfSubstance.From, out quantity); - - if (quantityType == typeof(AmplitudeRatio)) - return parser.TryParse(quantityString, formatProvider, AmplitudeRatio.From, out quantity); - - if (quantityType == typeof(Angle)) - return parser.TryParse(quantityString, formatProvider, Angle.From, out quantity); - - if (quantityType == typeof(ApparentEnergy)) - return parser.TryParse(quantityString, formatProvider, ApparentEnergy.From, out quantity); - - if (quantityType == typeof(ApparentPower)) - return parser.TryParse(quantityString, formatProvider, ApparentPower.From, out quantity); - - if (quantityType == typeof(Area)) - return parser.TryParse(quantityString, formatProvider, Area.From, out quantity); - - if (quantityType == typeof(AreaDensity)) - return parser.TryParse(quantityString, formatProvider, AreaDensity.From, out quantity); - - if (quantityType == typeof(AreaMomentOfInertia)) - return parser.TryParse(quantityString, formatProvider, AreaMomentOfInertia.From, out quantity); - - if (quantityType == typeof(BitRate)) - return parser.TryParse(quantityString, formatProvider, BitRate.From, out quantity); - - if (quantityType == typeof(BrakeSpecificFuelConsumption)) - return parser.TryParse(quantityString, formatProvider, BrakeSpecificFuelConsumption.From, out quantity); - - if (quantityType == typeof(Capacitance)) - return parser.TryParse(quantityString, formatProvider, Capacitance.From, out quantity); - - if (quantityType == typeof(CoefficientOfThermalExpansion)) - return parser.TryParse(quantityString, formatProvider, CoefficientOfThermalExpansion.From, out quantity); - - if (quantityType == typeof(Compressibility)) - return parser.TryParse(quantityString, formatProvider, Compressibility.From, out quantity); - - if (quantityType == typeof(Density)) - return parser.TryParse(quantityString, formatProvider, Density.From, out quantity); - - if (quantityType == typeof(Duration)) - return parser.TryParse(quantityString, formatProvider, Duration.From, out quantity); - - if (quantityType == typeof(DynamicViscosity)) - return parser.TryParse(quantityString, formatProvider, DynamicViscosity.From, out quantity); - - if (quantityType == typeof(ElectricAdmittance)) - return parser.TryParse(quantityString, formatProvider, ElectricAdmittance.From, out quantity); - - if (quantityType == typeof(ElectricCharge)) - return parser.TryParse(quantityString, formatProvider, ElectricCharge.From, out quantity); - - if (quantityType == typeof(ElectricChargeDensity)) - return parser.TryParse(quantityString, formatProvider, ElectricChargeDensity.From, out quantity); - - if (quantityType == typeof(ElectricConductance)) - return parser.TryParse(quantityString, formatProvider, ElectricConductance.From, out quantity); - - if (quantityType == typeof(ElectricConductivity)) - return parser.TryParse(quantityString, formatProvider, ElectricConductivity.From, out quantity); - - if (quantityType == typeof(ElectricCurrent)) - return parser.TryParse(quantityString, formatProvider, ElectricCurrent.From, out quantity); - - if (quantityType == typeof(ElectricCurrentDensity)) - return parser.TryParse(quantityString, formatProvider, ElectricCurrentDensity.From, out quantity); - - if (quantityType == typeof(ElectricCurrentGradient)) - return parser.TryParse(quantityString, formatProvider, ElectricCurrentGradient.From, out quantity); - - if (quantityType == typeof(ElectricField)) - return parser.TryParse(quantityString, formatProvider, ElectricField.From, out quantity); - - if (quantityType == typeof(ElectricInductance)) - return parser.TryParse(quantityString, formatProvider, ElectricInductance.From, out quantity); - - if (quantityType == typeof(ElectricPotential)) - return parser.TryParse(quantityString, formatProvider, ElectricPotential.From, out quantity); - - if (quantityType == typeof(ElectricPotentialAc)) - return parser.TryParse(quantityString, formatProvider, ElectricPotentialAc.From, out quantity); - - if (quantityType == typeof(ElectricPotentialChangeRate)) - return parser.TryParse(quantityString, formatProvider, ElectricPotentialChangeRate.From, out quantity); - - if (quantityType == typeof(ElectricPotentialDc)) - return parser.TryParse(quantityString, formatProvider, ElectricPotentialDc.From, out quantity); - - if (quantityType == typeof(ElectricResistance)) - return parser.TryParse(quantityString, formatProvider, ElectricResistance.From, out quantity); - - if (quantityType == typeof(ElectricResistivity)) - return parser.TryParse(quantityString, formatProvider, ElectricResistivity.From, out quantity); - - if (quantityType == typeof(ElectricSurfaceChargeDensity)) - return parser.TryParse(quantityString, formatProvider, ElectricSurfaceChargeDensity.From, out quantity); - - if (quantityType == typeof(Energy)) - return parser.TryParse(quantityString, formatProvider, Energy.From, out quantity); - - if (quantityType == typeof(EnergyDensity)) - return parser.TryParse(quantityString, formatProvider, EnergyDensity.From, out quantity); - - if (quantityType == typeof(Entropy)) - return parser.TryParse(quantityString, formatProvider, Entropy.From, out quantity); - - if (quantityType == typeof(Force)) - return parser.TryParse(quantityString, formatProvider, Force.From, out quantity); - - if (quantityType == typeof(ForceChangeRate)) - return parser.TryParse(quantityString, formatProvider, ForceChangeRate.From, out quantity); - - if (quantityType == typeof(ForcePerLength)) - return parser.TryParse(quantityString, formatProvider, ForcePerLength.From, out quantity); - - if (quantityType == typeof(Frequency)) - return parser.TryParse(quantityString, formatProvider, Frequency.From, out quantity); - - if (quantityType == typeof(FuelEfficiency)) - return parser.TryParse(quantityString, formatProvider, FuelEfficiency.From, out quantity); - - if (quantityType == typeof(HeatFlux)) - return parser.TryParse(quantityString, formatProvider, HeatFlux.From, out quantity); - - if (quantityType == typeof(HeatTransferCoefficient)) - return parser.TryParse(quantityString, formatProvider, HeatTransferCoefficient.From, out quantity); - - if (quantityType == typeof(Illuminance)) - return parser.TryParse(quantityString, formatProvider, Illuminance.From, out quantity); - - if (quantityType == typeof(Information)) - return parser.TryParse(quantityString, formatProvider, Information.From, out quantity); - - if (quantityType == typeof(Irradiance)) - return parser.TryParse(quantityString, formatProvider, Irradiance.From, out quantity); - - if (quantityType == typeof(Irradiation)) - return parser.TryParse(quantityString, formatProvider, Irradiation.From, out quantity); - - if (quantityType == typeof(Jerk)) - return parser.TryParse(quantityString, formatProvider, Jerk.From, out quantity); - - if (quantityType == typeof(KinematicViscosity)) - return parser.TryParse(quantityString, formatProvider, KinematicViscosity.From, out quantity); - - if (quantityType == typeof(LapseRate)) - return parser.TryParse(quantityString, formatProvider, LapseRate.From, out quantity); - - if (quantityType == typeof(Length)) - return parser.TryParse(quantityString, formatProvider, Length.From, out quantity); - - if (quantityType == typeof(Level)) - return parser.TryParse(quantityString, formatProvider, Level.From, out quantity); - - if (quantityType == typeof(LinearDensity)) - return parser.TryParse(quantityString, formatProvider, LinearDensity.From, out quantity); - - if (quantityType == typeof(LinearPowerDensity)) - return parser.TryParse(quantityString, formatProvider, LinearPowerDensity.From, out quantity); - - if (quantityType == typeof(Luminance)) - return parser.TryParse(quantityString, formatProvider, Luminance.From, out quantity); - - if (quantityType == typeof(Luminosity)) - return parser.TryParse(quantityString, formatProvider, Luminosity.From, out quantity); - - if (quantityType == typeof(LuminousFlux)) - return parser.TryParse(quantityString, formatProvider, LuminousFlux.From, out quantity); - - if (quantityType == typeof(LuminousIntensity)) - return parser.TryParse(quantityString, formatProvider, LuminousIntensity.From, out quantity); - - if (quantityType == typeof(MagneticField)) - return parser.TryParse(quantityString, formatProvider, MagneticField.From, out quantity); - - if (quantityType == typeof(MagneticFlux)) - return parser.TryParse(quantityString, formatProvider, MagneticFlux.From, out quantity); - - if (quantityType == typeof(Magnetization)) - return parser.TryParse(quantityString, formatProvider, Magnetization.From, out quantity); - - if (quantityType == typeof(Mass)) - return parser.TryParse(quantityString, formatProvider, Mass.From, out quantity); - - if (quantityType == typeof(MassConcentration)) - return parser.TryParse(quantityString, formatProvider, MassConcentration.From, out quantity); - - if (quantityType == typeof(MassFlow)) - return parser.TryParse(quantityString, formatProvider, MassFlow.From, out quantity); - - if (quantityType == typeof(MassFlux)) - return parser.TryParse(quantityString, formatProvider, MassFlux.From, out quantity); - - if (quantityType == typeof(MassFraction)) - return parser.TryParse(quantityString, formatProvider, MassFraction.From, out quantity); - - if (quantityType == typeof(MassMomentOfInertia)) - return parser.TryParse(quantityString, formatProvider, MassMomentOfInertia.From, out quantity); - - if (quantityType == typeof(MolarEnergy)) - return parser.TryParse(quantityString, formatProvider, MolarEnergy.From, out quantity); - - if (quantityType == typeof(MolarEntropy)) - return parser.TryParse(quantityString, formatProvider, MolarEntropy.From, out quantity); - - if (quantityType == typeof(Molarity)) - return parser.TryParse(quantityString, formatProvider, Molarity.From, out quantity); - - if (quantityType == typeof(MolarMass)) - return parser.TryParse(quantityString, formatProvider, MolarMass.From, out quantity); - - if (quantityType == typeof(Permeability)) - return parser.TryParse(quantityString, formatProvider, Permeability.From, out quantity); - - if (quantityType == typeof(Permittivity)) - return parser.TryParse(quantityString, formatProvider, Permittivity.From, out quantity); - - if (quantityType == typeof(PorousMediumPermeability)) - return parser.TryParse(quantityString, formatProvider, PorousMediumPermeability.From, out quantity); - - if (quantityType == typeof(Power)) - return parser.TryParse(quantityString, formatProvider, Power.From, out quantity); - - if (quantityType == typeof(PowerDensity)) - return parser.TryParse(quantityString, formatProvider, PowerDensity.From, out quantity); - - if (quantityType == typeof(PowerRatio)) - return parser.TryParse(quantityString, formatProvider, PowerRatio.From, out quantity); - - if (quantityType == typeof(Pressure)) - return parser.TryParse(quantityString, formatProvider, Pressure.From, out quantity); - - if (quantityType == typeof(PressureChangeRate)) - return parser.TryParse(quantityString, formatProvider, PressureChangeRate.From, out quantity); - - if (quantityType == typeof(Ratio)) - return parser.TryParse(quantityString, formatProvider, Ratio.From, out quantity); - - if (quantityType == typeof(RatioChangeRate)) - return parser.TryParse(quantityString, formatProvider, RatioChangeRate.From, out quantity); - - if (quantityType == typeof(ReactiveEnergy)) - return parser.TryParse(quantityString, formatProvider, ReactiveEnergy.From, out quantity); - - if (quantityType == typeof(ReactivePower)) - return parser.TryParse(quantityString, formatProvider, ReactivePower.From, out quantity); - - if (quantityType == typeof(ReciprocalArea)) - return parser.TryParse(quantityString, formatProvider, ReciprocalArea.From, out quantity); - - if (quantityType == typeof(ReciprocalLength)) - return parser.TryParse(quantityString, formatProvider, ReciprocalLength.From, out quantity); - - if (quantityType == typeof(RelativeHumidity)) - return parser.TryParse(quantityString, formatProvider, RelativeHumidity.From, out quantity); - - if (quantityType == typeof(RotationalAcceleration)) - return parser.TryParse(quantityString, formatProvider, RotationalAcceleration.From, out quantity); - - if (quantityType == typeof(RotationalSpeed)) - return parser.TryParse(quantityString, formatProvider, RotationalSpeed.From, out quantity); - - if (quantityType == typeof(RotationalStiffness)) - return parser.TryParse(quantityString, formatProvider, RotationalStiffness.From, out quantity); - - if (quantityType == typeof(RotationalStiffnessPerLength)) - return parser.TryParse(quantityString, formatProvider, RotationalStiffnessPerLength.From, out quantity); - - if (quantityType == typeof(Scalar)) - return parser.TryParse(quantityString, formatProvider, Scalar.From, out quantity); - - if (quantityType == typeof(SolidAngle)) - return parser.TryParse(quantityString, formatProvider, SolidAngle.From, out quantity); - - if (quantityType == typeof(SpecificEnergy)) - return parser.TryParse(quantityString, formatProvider, SpecificEnergy.From, out quantity); - - if (quantityType == typeof(SpecificEntropy)) - return parser.TryParse(quantityString, formatProvider, SpecificEntropy.From, out quantity); - - if (quantityType == typeof(SpecificFuelConsumption)) - return parser.TryParse(quantityString, formatProvider, SpecificFuelConsumption.From, out quantity); - - if (quantityType == typeof(SpecificVolume)) - return parser.TryParse(quantityString, formatProvider, SpecificVolume.From, out quantity); - - if (quantityType == typeof(SpecificWeight)) - return parser.TryParse(quantityString, formatProvider, SpecificWeight.From, out quantity); - - if (quantityType == typeof(Speed)) - return parser.TryParse(quantityString, formatProvider, Speed.From, out quantity); - - if (quantityType == typeof(StandardVolumeFlow)) - return parser.TryParse(quantityString, formatProvider, StandardVolumeFlow.From, out quantity); - - if (quantityType == typeof(Temperature)) - return parser.TryParse(quantityString, formatProvider, Temperature.From, out quantity); - - if (quantityType == typeof(TemperatureChangeRate)) - return parser.TryParse(quantityString, formatProvider, TemperatureChangeRate.From, out quantity); - - if (quantityType == typeof(TemperatureDelta)) - return parser.TryParse(quantityString, formatProvider, TemperatureDelta.From, out quantity); - - if (quantityType == typeof(TemperatureGradient)) - return parser.TryParse(quantityString, formatProvider, TemperatureGradient.From, out quantity); - - if (quantityType == typeof(ThermalConductivity)) - return parser.TryParse(quantityString, formatProvider, ThermalConductivity.From, out quantity); - - if (quantityType == typeof(ThermalResistance)) - return parser.TryParse(quantityString, formatProvider, ThermalResistance.From, out quantity); - - if (quantityType == typeof(Torque)) - return parser.TryParse(quantityString, formatProvider, Torque.From, out quantity); - - if (quantityType == typeof(TorquePerLength)) - return parser.TryParse(quantityString, formatProvider, TorquePerLength.From, out quantity); - - if (quantityType == typeof(Turbidity)) - return parser.TryParse(quantityString, formatProvider, Turbidity.From, out quantity); - - if (quantityType == typeof(VitaminA)) - return parser.TryParse(quantityString, formatProvider, VitaminA.From, out quantity); - - if (quantityType == typeof(Volume)) - return parser.TryParse(quantityString, formatProvider, Volume.From, out quantity); - - if (quantityType == typeof(VolumeConcentration)) - return parser.TryParse(quantityString, formatProvider, VolumeConcentration.From, out quantity); - - if (quantityType == typeof(VolumeFlow)) - return parser.TryParse(quantityString, formatProvider, VolumeFlow.From, out quantity); - - if (quantityType == typeof(VolumeFlowPerArea)) - return parser.TryParse(quantityString, formatProvider, VolumeFlowPerArea.From, out quantity); - - if (quantityType == typeof(VolumePerLength)) - return parser.TryParse(quantityString, formatProvider, VolumePerLength.From, out quantity); - - if (quantityType == typeof(VolumetricHeatCapacity)) - return parser.TryParse(quantityString, formatProvider, VolumetricHeatCapacity.From, out quantity); - - if (quantityType == typeof(WarpingMomentOfInertia)) - return parser.TryParse(quantityString, formatProvider, WarpingMomentOfInertia.From, out quantity); - - throw new ArgumentException( - $"Type {quantityType} is not a known quantity type. Did you pass in a third-party quantity type defined outside UnitsNet library?"); - } - - internal static IEnumerable 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(LapseRate); - 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.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs deleted file mode 100644 index d4fb3bf9fb..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/QuantityType.g.cs +++ /dev/null @@ -1,154 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace - -using System; - -namespace UnitsNet -{ - /// - /// Lists all generated quantities with the same name as the quantity struct type, - /// such as Length, Mass, Force etc. - /// This is useful for populating options in the UI, such as creating a generic conversion - /// tool with inputValue, quantityName, fromUnit and toUnit selectors. - /// - [Obsolete("QuantityType will be removed in the future. Use the QuantityInfo class instead.")] - public enum QuantityType - { - Undefined = 0, - Acceleration, - AmountOfSubstance, - AmplitudeRatio, - Angle, - ApparentEnergy, - ApparentPower, - Area, - AreaDensity, - AreaMomentOfInertia, - BitRate, - BrakeSpecificFuelConsumption, - Capacitance, - CoefficientOfThermalExpansion, - Compressibility, - Density, - Duration, - DynamicViscosity, - ElectricAdmittance, - ElectricCharge, - ElectricChargeDensity, - ElectricConductance, - ElectricConductivity, - ElectricCurrent, - ElectricCurrentDensity, - ElectricCurrentGradient, - ElectricField, - ElectricInductance, - ElectricPotential, - ElectricPotentialAc, - ElectricPotentialChangeRate, - ElectricPotentialDc, - ElectricResistance, - ElectricResistivity, - ElectricSurfaceChargeDensity, - Energy, - EnergyDensity, - Entropy, - Force, - ForceChangeRate, - ForcePerLength, - Frequency, - FuelEfficiency, - HeatFlux, - HeatTransferCoefficient, - Illuminance, - Information, - Irradiance, - Irradiation, - Jerk, - KinematicViscosity, - LapseRate, - Length, - Level, - LinearDensity, - LinearPowerDensity, - Luminance, - Luminosity, - LuminousFlux, - LuminousIntensity, - MagneticField, - MagneticFlux, - Magnetization, - Mass, - MassConcentration, - MassFlow, - MassFlux, - MassFraction, - MassMomentOfInertia, - MolarEnergy, - MolarEntropy, - Molarity, - MolarMass, - Permeability, - Permittivity, - PorousMediumPermeability, - Power, - PowerDensity, - PowerRatio, - Pressure, - PressureChangeRate, - Ratio, - RatioChangeRate, - ReactiveEnergy, - ReactivePower, - ReciprocalArea, - ReciprocalLength, - RelativeHumidity, - RotationalAcceleration, - RotationalSpeed, - RotationalStiffness, - RotationalStiffnessPerLength, - Scalar, - SolidAngle, - SpecificEnergy, - SpecificEntropy, - SpecificFuelConsumption, - SpecificVolume, - SpecificWeight, - Speed, - StandardVolumeFlow, - Temperature, - TemperatureChangeRate, - TemperatureDelta, - TemperatureGradient, - ThermalConductivity, - ThermalResistance, - Torque, - TorquePerLength, - Turbidity, - VitaminA, - Volume, - VolumeConcentration, - VolumeFlow, - VolumeFlowPerArea, - VolumePerLength, - VolumetricHeatCapacity, - WarpingMomentOfInertia, - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AccelerationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AccelerationUnit.g.cs deleted file mode 100644 index 149fda76fb..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AccelerationUnit.g.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AccelerationUnit - { - Undefined = 0, - CentimeterPerSecondSquared, - DecimeterPerSecondSquared, - FootPerSecondSquared, - InchPerSecondSquared, - KilometerPerSecondSquared, - KnotPerHour, - KnotPerMinute, - KnotPerSecond, - MeterPerSecondSquared, - MicrometerPerSecondSquared, - MillimeterPerSecondSquared, - MillistandardGravity, - NanometerPerSecondSquared, - StandardGravity, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs deleted file mode 100644 index ebd46a97d7..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs +++ /dev/null @@ -1,47 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AmountOfSubstanceUnit - { - Undefined = 0, - Centimole, - CentipoundMole, - Decimole, - DecipoundMole, - Kilomole, - KilopoundMole, - Megamole, - Micromole, - MicropoundMole, - Millimole, - MillipoundMole, - Mole, - Nanomole, - NanopoundMole, - PoundMole, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AmplitudeRatioUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AmplitudeRatioUnit.g.cs deleted file mode 100644 index b7bb6ae224..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AmplitudeRatioUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AmplitudeRatioUnit - { - Undefined = 0, - DecibelMicrovolt, - DecibelMillivolt, - DecibelUnloaded, - DecibelVolt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AngleUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AngleUnit.g.cs deleted file mode 100644 index b61f169b80..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AngleUnit.g.cs +++ /dev/null @@ -1,48 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AngleUnit - { - Undefined = 0, - Arcminute, - Arcsecond, - Centiradian, - Deciradian, - Degree, - Gradian, - Microdegree, - Microradian, - Millidegree, - Milliradian, - Nanodegree, - Nanoradian, - NatoMil, - Radian, - Revolution, - Tilt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ApparentEnergyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ApparentEnergyUnit.g.cs deleted file mode 100644 index e7b4f42ee4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ApparentEnergyUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ApparentEnergyUnit - { - Undefined = 0, - KilovoltampereHour, - MegavoltampereHour, - VoltampereHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ApparentPowerUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ApparentPowerUnit.g.cs deleted file mode 100644 index cd5563c699..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ApparentPowerUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ApparentPowerUnit - { - Undefined = 0, - Gigavoltampere, - Kilovoltampere, - Megavoltampere, - Voltampere, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaDensityUnit.g.cs deleted file mode 100644 index 8b48f12629..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaDensityUnit.g.cs +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AreaDensityUnit - { - Undefined = 0, - - /// - /// Also known as grammage for paper industry. In fiber industry used with abbreviation 'gsm'. - /// - /// https://en.wikipedia.org/wiki/Grammage - GramPerSquareMeter, - KilogramPerSquareMeter, - MilligramPerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs deleted file mode 100644 index 3ca2fc3574..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AreaMomentOfInertiaUnit - { - Undefined = 0, - CentimeterToTheFourth, - DecimeterToTheFourth, - FootToTheFourth, - InchToTheFourth, - MeterToTheFourth, - MillimeterToTheFourth, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaUnit.g.cs deleted file mode 100644 index 2db395608c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/AreaUnit.g.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum AreaUnit - { - Undefined = 0, - Acre, - Hectare, - SquareCentimeter, - SquareDecimeter, - SquareFoot, - SquareInch, - SquareKilometer, - SquareMeter, - SquareMicrometer, - SquareMile, - SquareMillimeter, - SquareNauticalMile, - SquareYard, - UsSurveySquareFoot, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/BitRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/BitRateUnit.g.cs deleted file mode 100644 index e6328d9e65..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/BitRateUnit.g.cs +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum BitRateUnit - { - Undefined = 0, - BitPerSecond, - BytePerSecond, - ExabitPerSecond, - ExabytePerSecond, - ExbibitPerSecond, - ExbibytePerSecond, - GibibitPerSecond, - GibibytePerSecond, - GigabitPerSecond, - GigabytePerSecond, - KibibitPerSecond, - KibibytePerSecond, - KilobitPerSecond, - KilobytePerSecond, - MebibitPerSecond, - MebibytePerSecond, - MegabitPerSecond, - MegabytePerSecond, - PebibitPerSecond, - PebibytePerSecond, - PetabitPerSecond, - PetabytePerSecond, - TebibitPerSecond, - TebibytePerSecond, - TerabitPerSecond, - TerabytePerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs deleted file mode 100644 index bb10b001c3..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum BrakeSpecificFuelConsumptionUnit - { - Undefined = 0, - GramPerKiloWattHour, - KilogramPerJoule, - - /// - /// The pound per horse power hour uses mechanical horse power and the imperial pound - /// - PoundPerMechanicalHorsepowerHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CapacitanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CapacitanceUnit.g.cs deleted file mode 100644 index 9b6a538fb9..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CapacitanceUnit.g.cs +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum CapacitanceUnit - { - Undefined = 0, - Farad, - Kilofarad, - Megafarad, - Microfarad, - Millifarad, - Nanofarad, - Picofarad, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs deleted file mode 100644 index 9db9fa9d0d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum CoefficientOfThermalExpansionUnit - { - Undefined = 0, - InverseDegreeCelsius, - InverseDegreeFahrenheit, - InverseKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CompressibilityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CompressibilityUnit.g.cs deleted file mode 100644 index 5b3e4f4514..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/CompressibilityUnit.g.cs +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum CompressibilityUnit - { - Undefined = 0, - InverseAtmosphere, - InverseBar, - InverseKilopascal, - InverseMegapascal, - InverseMillibar, - InversePascal, - InversePoundForcePerSquareInch, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DensityUnit.g.cs deleted file mode 100644 index 62795a2b36..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DensityUnit.g.cs +++ /dev/null @@ -1,83 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum DensityUnit - { - Undefined = 0, - CentigramPerDeciliter, - CentigramPerLiter, - CentigramPerMilliliter, - DecigramPerDeciliter, - DecigramPerLiter, - DecigramPerMilliliter, - GramPerCubicCentimeter, - GramPerCubicFoot, - GramPerCubicInch, - GramPerCubicMeter, - GramPerCubicMillimeter, - GramPerDeciliter, - GramPerLiter, - GramPerMilliliter, - KilogramPerCubicCentimeter, - KilogramPerCubicMeter, - KilogramPerCubicMillimeter, - KilogramPerLiter, - KilopoundPerCubicFoot, - KilopoundPerCubicInch, - MicrogramPerCubicMeter, - MicrogramPerDeciliter, - MicrogramPerLiter, - MicrogramPerMilliliter, - MilligramPerCubicMeter, - MilligramPerDeciliter, - MilligramPerLiter, - MilligramPerMilliliter, - NanogramPerDeciliter, - NanogramPerLiter, - NanogramPerMilliliter, - PicogramPerDeciliter, - PicogramPerLiter, - PicogramPerMilliliter, - PoundPerCubicCentimeter, - PoundPerCubicFoot, - PoundPerCubicInch, - PoundPerCubicMeter, - PoundPerCubicMillimeter, - PoundPerImperialGallon, - PoundPerUSGallon, - SlugPerCubicCentimeter, - SlugPerCubicFoot, - SlugPerCubicInch, - SlugPerCubicMeter, - SlugPerCubicMillimeter, - TonnePerCubicCentimeter, - TonnePerCubicFoot, - TonnePerCubicInch, - TonnePerCubicMeter, - TonnePerCubicMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DurationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DurationUnit.g.cs deleted file mode 100644 index f9ae0ea6c4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DurationUnit.g.cs +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum DurationUnit - { - Undefined = 0, - Day, - Hour, - JulianYear, - Microsecond, - Millisecond, - Minute, - Month30, - Nanosecond, - Second, - Week, - Year365, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DynamicViscosityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DynamicViscosityUnit.g.cs deleted file mode 100644 index a0d6fc8e13..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/DynamicViscosityUnit.g.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum DynamicViscosityUnit - { - Undefined = 0, - Centipoise, - MicropascalSecond, - MillipascalSecond, - NewtonSecondPerMeterSquared, - PascalSecond, - Poise, - PoundForceSecondPerSquareFoot, - PoundForceSecondPerSquareInch, - PoundPerFootSecond, - Reyn, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs deleted file mode 100644 index 21e8f4edfa..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricAdmittanceUnit - { - Undefined = 0, - Microsiemens, - Millisiemens, - Nanosiemens, - Siemens, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs deleted file mode 100644 index 8797383f4a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricChargeDensityUnit - { - Undefined = 0, - CoulombPerCubicMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricChargeUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricChargeUnit.g.cs deleted file mode 100644 index 65c4b8b58d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricChargeUnit.g.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricChargeUnit - { - Undefined = 0, - AmpereHour, - Coulomb, - KiloampereHour, - MegaampereHour, - MilliampereHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricConductanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricConductanceUnit.g.cs deleted file mode 100644 index 5b852833d7..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricConductanceUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricConductanceUnit - { - Undefined = 0, - Microsiemens, - Millisiemens, - Siemens, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricConductivityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricConductivityUnit.g.cs deleted file mode 100644 index 7ae73ba419..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricConductivityUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricConductivityUnit - { - Undefined = 0, - MicrosiemensPerCentimeter, - MillisiemensPerCentimeter, - SiemensPerCentimeter, - SiemensPerFoot, - SiemensPerInch, - SiemensPerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs deleted file mode 100644 index 9a0a8c9715..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricCurrentDensityUnit - { - Undefined = 0, - AmperePerSquareFoot, - AmperePerSquareInch, - AmperePerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs deleted file mode 100644 index ec7e9f0e02..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricCurrentGradientUnit - { - Undefined = 0, - AmperePerMicrosecond, - AmperePerMillisecond, - AmperePerNanosecond, - AmperePerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentUnit.g.cs deleted file mode 100644 index a2b690d5c4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricCurrentUnit.g.cs +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricCurrentUnit - { - Undefined = 0, - Ampere, - Centiampere, - Kiloampere, - Megaampere, - Microampere, - Milliampere, - Nanoampere, - Picoampere, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricFieldUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricFieldUnit.g.cs deleted file mode 100644 index c3710d6ad6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricFieldUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricFieldUnit - { - Undefined = 0, - VoltPerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricInductanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricInductanceUnit.g.cs deleted file mode 100644 index 1cac8bbe3c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricInductanceUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricInductanceUnit - { - Undefined = 0, - Henry, - Microhenry, - Millihenry, - Nanohenry, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs deleted file mode 100644 index 87ba58a573..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricPotentialAcUnit - { - Undefined = 0, - KilovoltAc, - MegavoltAc, - MicrovoltAc, - MillivoltAc, - VoltAc, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs deleted file mode 100644 index d77a1dd97b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs +++ /dev/null @@ -1,52 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricPotentialChangeRateUnit - { - Undefined = 0, - KilovoltPerHour, - KilovoltPerMicrosecond, - KilovoltPerMinute, - KilovoltPerSecond, - MegavoltPerHour, - MegavoltPerMicrosecond, - MegavoltPerMinute, - MegavoltPerSecond, - MicrovoltPerHour, - MicrovoltPerMicrosecond, - MicrovoltPerMinute, - MicrovoltPerSecond, - MillivoltPerHour, - MillivoltPerMicrosecond, - MillivoltPerMinute, - MillivoltPerSecond, - VoltPerHour, - VoltPerMicrosecond, - VoltPerMinute, - VoltPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs deleted file mode 100644 index 8743571009..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricPotentialDcUnit - { - Undefined = 0, - KilovoltDc, - MegavoltDc, - MicrovoltDc, - MillivoltDc, - VoltDc, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialUnit.g.cs deleted file mode 100644 index a50136ad6b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricPotentialUnit.g.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricPotentialUnit - { - Undefined = 0, - Kilovolt, - Megavolt, - Microvolt, - Millivolt, - Volt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricResistanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricResistanceUnit.g.cs deleted file mode 100644 index e0cdbd4632..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricResistanceUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricResistanceUnit - { - Undefined = 0, - Gigaohm, - Kiloohm, - Megaohm, - Microohm, - Milliohm, - Ohm, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricResistivityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricResistivityUnit.g.cs deleted file mode 100644 index cb6360eda3..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricResistivityUnit.g.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricResistivityUnit - { - Undefined = 0, - KiloohmCentimeter, - KiloohmMeter, - MegaohmCentimeter, - MegaohmMeter, - MicroohmCentimeter, - MicroohmMeter, - MilliohmCentimeter, - MilliohmMeter, - NanoohmCentimeter, - NanoohmMeter, - OhmCentimeter, - OhmMeter, - PicoohmCentimeter, - PicoohmMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs deleted file mode 100644 index 1e96388035..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ElectricSurfaceChargeDensityUnit - { - Undefined = 0, - CoulombPerSquareCentimeter, - CoulombPerSquareInch, - CoulombPerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/EnergyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/EnergyUnit.g.cs deleted file mode 100644 index 4b75a4e096..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/EnergyUnit.g.cs +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum EnergyUnit - { - Undefined = 0, - BritishThermalUnit, - Calorie, - DecathermEc, - DecathermImperial, - DecathermUs, - ElectronVolt, - Erg, - FootPound, - GigabritishThermalUnit, - GigaelectronVolt, - Gigajoule, - GigawattDay, - GigawattHour, - HorsepowerHour, - Joule, - KilobritishThermalUnit, - Kilocalorie, - KiloelectronVolt, - Kilojoule, - KilowattDay, - KilowattHour, - MegabritishThermalUnit, - Megacalorie, - MegaelectronVolt, - Megajoule, - MegawattDay, - MegawattHour, - Millijoule, - Petajoule, - TeraelectronVolt, - Terajoule, - TerawattDay, - TerawattHour, - ThermEc, - ThermImperial, - ThermUs, - WattDay, - WattHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/EntropyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/EntropyUnit.g.cs deleted file mode 100644 index 527b5b7f3c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/EntropyUnit.g.cs +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum EntropyUnit - { - Undefined = 0, - CaloriePerKelvin, - JoulePerDegreeCelsius, - JoulePerKelvin, - KilocaloriePerKelvin, - KilojoulePerDegreeCelsius, - KilojoulePerKelvin, - MegajoulePerKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForceChangeRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForceChangeRateUnit.g.cs deleted file mode 100644 index 872ff7774c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForceChangeRateUnit.g.cs +++ /dev/null @@ -1,47 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ForceChangeRateUnit - { - Undefined = 0, - CentinewtonPerSecond, - DecanewtonPerMinute, - DecanewtonPerSecond, - DecinewtonPerSecond, - KilonewtonPerMinute, - KilonewtonPerSecond, - KilopoundForcePerMinute, - KilopoundForcePerSecond, - MicronewtonPerSecond, - MillinewtonPerSecond, - NanonewtonPerSecond, - NewtonPerMinute, - NewtonPerSecond, - PoundForcePerMinute, - PoundForcePerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForcePerLengthUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForcePerLengthUnit.g.cs deleted file mode 100644 index e5f004605f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForcePerLengthUnit.g.cs +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ForcePerLengthUnit - { - Undefined = 0, - CentinewtonPerCentimeter, - CentinewtonPerMeter, - CentinewtonPerMillimeter, - DecanewtonPerCentimeter, - DecanewtonPerMeter, - DecanewtonPerMillimeter, - DecinewtonPerCentimeter, - DecinewtonPerMeter, - DecinewtonPerMillimeter, - KilogramForcePerCentimeter, - KilogramForcePerMeter, - KilogramForcePerMillimeter, - KilonewtonPerCentimeter, - KilonewtonPerMeter, - KilonewtonPerMillimeter, - KilopoundForcePerFoot, - KilopoundForcePerInch, - MeganewtonPerCentimeter, - MeganewtonPerMeter, - MeganewtonPerMillimeter, - MicronewtonPerCentimeter, - MicronewtonPerMeter, - MicronewtonPerMillimeter, - MillinewtonPerCentimeter, - MillinewtonPerMeter, - MillinewtonPerMillimeter, - NanonewtonPerCentimeter, - NanonewtonPerMeter, - NanonewtonPerMillimeter, - NewtonPerCentimeter, - NewtonPerMeter, - NewtonPerMillimeter, - PoundForcePerFoot, - PoundForcePerInch, - PoundForcePerYard, - TonneForcePerCentimeter, - TonneForcePerMeter, - TonneForcePerMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForceUnit.g.cs deleted file mode 100644 index b3124108bd..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ForceUnit.g.cs +++ /dev/null @@ -1,52 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ForceUnit - { - Undefined = 0, - Decanewton, - Dyn, - KilogramForce, - Kilonewton, - KiloPond, - KilopoundForce, - Meganewton, - Micronewton, - Millinewton, - Newton, - OunceForce, - Poundal, - PoundForce, - - /// - /// 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. - /// - /// https://en.wikipedia.org/wiki/Ton-force#Short_ton-force - ShortTonForce, - TonneForce, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FrequencyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FrequencyUnit.g.cs deleted file mode 100644 index fd5c104061..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FrequencyUnit.g.cs +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum FrequencyUnit - { - Undefined = 0, - BeatPerMinute, - BUnit, - CyclePerHour, - CyclePerMinute, - Gigahertz, - Hertz, - Kilohertz, - Megahertz, - PerSecond, - RadianPerSecond, - Terahertz, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FuelEfficiencyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FuelEfficiencyUnit.g.cs deleted file mode 100644 index 7dbfd0ab36..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/FuelEfficiencyUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum FuelEfficiencyUnit - { - Undefined = 0, - KilometerPerLiter, - LiterPer100Kilometers, - MilePerUkGallon, - MilePerUsGallon, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/HeatFluxUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/HeatFluxUnit.g.cs deleted file mode 100644 index bc76552e32..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/HeatFluxUnit.g.cs +++ /dev/null @@ -1,50 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum HeatFluxUnit - { - Undefined = 0, - BtuPerHourSquareFoot, - BtuPerMinuteSquareFoot, - BtuPerSecondSquareFoot, - BtuPerSecondSquareInch, - CaloriePerSecondSquareCentimeter, - CentiwattPerSquareMeter, - DeciwattPerSquareMeter, - KilocaloriePerHourSquareMeter, - KilocaloriePerSecondSquareCentimeter, - KilowattPerSquareMeter, - MicrowattPerSquareMeter, - MilliwattPerSquareMeter, - NanowattPerSquareMeter, - PoundForcePerFootSecond, - PoundPerSecondCubed, - WattPerSquareFoot, - WattPerSquareInch, - WattPerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs deleted file mode 100644 index 6494d31478..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum HeatTransferCoefficientUnit - { - Undefined = 0, - BtuPerSquareFootDegreeFahrenheit, - WattPerSquareMeterCelsius, - WattPerSquareMeterKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IlluminanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IlluminanceUnit.g.cs deleted file mode 100644 index 3584e96825..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IlluminanceUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum IlluminanceUnit - { - Undefined = 0, - Kilolux, - Lux, - Megalux, - Millilux, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/InformationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/InformationUnit.g.cs deleted file mode 100644 index 2986de4b20..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/InformationUnit.g.cs +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum InformationUnit - { - Undefined = 0, - Bit, - Byte, - Exabit, - Exabyte, - Exbibit, - Exbibyte, - Gibibit, - Gibibyte, - Gigabit, - Gigabyte, - Kibibit, - Kibibyte, - Kilobit, - Kilobyte, - Mebibit, - Mebibyte, - Megabit, - Megabyte, - Pebibit, - Pebibyte, - Petabit, - Petabyte, - Tebibit, - Tebibyte, - Terabit, - Terabyte, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IrradianceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IrradianceUnit.g.cs deleted file mode 100644 index 285e771afa..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IrradianceUnit.g.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum IrradianceUnit - { - Undefined = 0, - KilowattPerSquareCentimeter, - KilowattPerSquareMeter, - MegawattPerSquareCentimeter, - MegawattPerSquareMeter, - MicrowattPerSquareCentimeter, - MicrowattPerSquareMeter, - MilliwattPerSquareCentimeter, - MilliwattPerSquareMeter, - NanowattPerSquareCentimeter, - NanowattPerSquareMeter, - PicowattPerSquareCentimeter, - PicowattPerSquareMeter, - WattPerSquareCentimeter, - WattPerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IrradiationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IrradiationUnit.g.cs deleted file mode 100644 index 1a13e8d425..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/IrradiationUnit.g.cs +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum IrradiationUnit - { - Undefined = 0, - JoulePerSquareCentimeter, - JoulePerSquareMeter, - JoulePerSquareMillimeter, - KilojoulePerSquareMeter, - KilowattHourPerSquareMeter, - MillijoulePerSquareCentimeter, - WattHourPerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/JerkUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/JerkUnit.g.cs deleted file mode 100644 index f269be60c8..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/JerkUnit.g.cs +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum JerkUnit - { - Undefined = 0, - CentimeterPerSecondCubed, - DecimeterPerSecondCubed, - FootPerSecondCubed, - InchPerSecondCubed, - KilometerPerSecondCubed, - MeterPerSecondCubed, - MicrometerPerSecondCubed, - MillimeterPerSecondCubed, - MillistandardGravitiesPerSecond, - NanometerPerSecondCubed, - StandardGravitiesPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/KinematicViscosityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/KinematicViscosityUnit.g.cs deleted file mode 100644 index af0c4a0e22..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/KinematicViscosityUnit.g.cs +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum KinematicViscosityUnit - { - Undefined = 0, - Centistokes, - Decistokes, - Kilostokes, - Microstokes, - Millistokes, - Nanostokes, - SquareFootPerSecond, - SquareMeterPerSecond, - Stokes, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LapseRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LapseRateUnit.g.cs deleted file mode 100644 index 0db5758f3e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LapseRateUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LapseRateUnit - { - Undefined = 0, - DegreeCelsiusPerKilometer, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LengthUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LengthUnit.g.cs deleted file mode 100644 index c95b043825..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LengthUnit.g.cs +++ /dev/null @@ -1,98 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LengthUnit - { - Undefined = 0, - - /// - /// Angstrom is a metric unit of length equal to 1e-10 meter - /// - /// https://en.wikipedia.org/wiki/Angstrom - Angstrom, - - /// - /// One Astronomical Unit is the distance from the solar system Star, the sun, to planet Earth. - /// - /// https://en.wikipedia.org/wiki/Astronomical_unit - AstronomicalUnit, - Centimeter, - Chain, - - /// - /// 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). - /// - /// https://en.wikipedia.org/wiki/Data_mile - DataMile, - Decameter, - Decimeter, - DtpPica, - DtpPoint, - Fathom, - Foot, - Hand, - Hectometer, - Inch, - KilolightYear, - Kilometer, - Kiloparsec, - - /// - /// A Light Year (ly) is the distance that light travel during an Earth year, ie 365 days. - /// - /// https://en.wikipedia.org/wiki/Light-year - LightYear, - MegalightYear, - Megaparsec, - Meter, - Microinch, - Micrometer, - Mil, - Mile, - Millimeter, - Nanometer, - NauticalMile, - - /// - /// A parsec is defined as the distance at which one astronomical unit (AU) subtends an angle of one arcsecond. - /// - /// https://en.wikipedia.org/wiki/Parsec - Parsec, - PrinterPica, - PrinterPoint, - Shackle, - - /// - /// Solar radius is a ratio unit to the radius of the solar system star, the sun. - /// - /// https://en.wikipedia.org/wiki/Stellar_classification - SolarRadius, - Twip, - UsSurveyFoot, - Yard, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LevelUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LevelUnit.g.cs deleted file mode 100644 index d1cd5c65ed..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LevelUnit.g.cs +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LevelUnit - { - Undefined = 0, - Decibel, - Neper, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LinearDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LinearDensityUnit.g.cs deleted file mode 100644 index 70a4f47764..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LinearDensityUnit.g.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LinearDensityUnit - { - Undefined = 0, - GramPerCentimeter, - GramPerMeter, - GramPerMillimeter, - KilogramPerCentimeter, - KilogramPerMeter, - KilogramPerMillimeter, - MicrogramPerCentimeter, - MicrogramPerMeter, - MicrogramPerMillimeter, - MilligramPerCentimeter, - MilligramPerMeter, - MilligramPerMillimeter, - PoundPerFoot, - PoundPerInch, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LinearPowerDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LinearPowerDensityUnit.g.cs deleted file mode 100644 index 0f744effb5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LinearPowerDensityUnit.g.cs +++ /dev/null @@ -1,57 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LinearPowerDensityUnit - { - Undefined = 0, - GigawattPerCentimeter, - GigawattPerFoot, - GigawattPerInch, - GigawattPerMeter, - GigawattPerMillimeter, - KilowattPerCentimeter, - KilowattPerFoot, - KilowattPerInch, - KilowattPerMeter, - KilowattPerMillimeter, - MegawattPerCentimeter, - MegawattPerFoot, - MegawattPerInch, - MegawattPerMeter, - MegawattPerMillimeter, - MilliwattPerCentimeter, - MilliwattPerFoot, - MilliwattPerInch, - MilliwattPerMeter, - MilliwattPerMillimeter, - WattPerCentimeter, - WattPerFoot, - WattPerInch, - WattPerMeter, - WattPerMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminosityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminosityUnit.g.cs deleted file mode 100644 index 309e51093d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminosityUnit.g.cs +++ /dev/null @@ -1,47 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LuminosityUnit - { - Undefined = 0, - Decawatt, - Deciwatt, - Femtowatt, - Gigawatt, - Kilowatt, - Megawatt, - Microwatt, - Milliwatt, - Nanowatt, - Petawatt, - Picowatt, - /// https://www.britannica.com/science/luminosity - SolarLuminosity, - Terawatt, - Watt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminousFluxUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminousFluxUnit.g.cs deleted file mode 100644 index 7d3122939f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminousFluxUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LuminousFluxUnit - { - Undefined = 0, - Lumen, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminousIntensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminousIntensityUnit.g.cs deleted file mode 100644 index 16feeb4596..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/LuminousIntensityUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum LuminousIntensityUnit - { - Undefined = 0, - Candela, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagneticFieldUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagneticFieldUnit.g.cs deleted file mode 100644 index 5ce5acdc3f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagneticFieldUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MagneticFieldUnit - { - Undefined = 0, - Gauss, - Microtesla, - Milligauss, - Millitesla, - Nanotesla, - Tesla, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagneticFluxUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagneticFluxUnit.g.cs deleted file mode 100644 index 241a0fc57b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagneticFluxUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MagneticFluxUnit - { - Undefined = 0, - Weber, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagnetizationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagnetizationUnit.g.cs deleted file mode 100644 index 96438162e4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MagnetizationUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MagnetizationUnit - { - Undefined = 0, - AmperePerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassConcentrationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassConcentrationUnit.g.cs deleted file mode 100644 index 75513af502..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassConcentrationUnit.g.cs +++ /dev/null @@ -1,81 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MassConcentrationUnit - { - Undefined = 0, - CentigramPerDeciliter, - CentigramPerLiter, - CentigramPerMicroliter, - CentigramPerMilliliter, - DecigramPerDeciliter, - DecigramPerLiter, - DecigramPerMicroliter, - DecigramPerMilliliter, - GramPerCubicCentimeter, - GramPerCubicMeter, - GramPerCubicMillimeter, - GramPerDeciliter, - GramPerLiter, - GramPerMicroliter, - GramPerMilliliter, - KilogramPerCubicCentimeter, - KilogramPerCubicMeter, - KilogramPerCubicMillimeter, - KilogramPerLiter, - KilopoundPerCubicFoot, - KilopoundPerCubicInch, - MicrogramPerCubicMeter, - MicrogramPerDeciliter, - MicrogramPerLiter, - MicrogramPerMicroliter, - MicrogramPerMilliliter, - MilligramPerCubicMeter, - MilligramPerDeciliter, - MilligramPerLiter, - MilligramPerMicroliter, - MilligramPerMilliliter, - NanogramPerDeciliter, - NanogramPerLiter, - NanogramPerMicroliter, - NanogramPerMilliliter, - OuncePerImperialGallon, - OuncePerUSGallon, - PicogramPerDeciliter, - PicogramPerLiter, - PicogramPerMicroliter, - PicogramPerMilliliter, - PoundPerCubicFoot, - PoundPerCubicInch, - PoundPerImperialGallon, - PoundPerUSGallon, - SlugPerCubicFoot, - TonnePerCubicCentimeter, - TonnePerCubicMeter, - TonnePerCubicMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFlowUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFlowUnit.g.cs deleted file mode 100644 index acf8b9cba6..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFlowUnit.g.cs +++ /dev/null @@ -1,65 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MassFlowUnit - { - Undefined = 0, - CentigramPerDay, - CentigramPerSecond, - DecagramPerDay, - DecagramPerSecond, - DecigramPerDay, - DecigramPerSecond, - GramPerDay, - GramPerHour, - GramPerSecond, - HectogramPerDay, - HectogramPerSecond, - KilogramPerDay, - KilogramPerHour, - KilogramPerMinute, - KilogramPerSecond, - MegagramPerDay, - MegapoundPerDay, - MegapoundPerHour, - MegapoundPerMinute, - MegapoundPerSecond, - MicrogramPerDay, - MicrogramPerSecond, - MilligramPerDay, - MilligramPerSecond, - NanogramPerDay, - NanogramPerSecond, - PoundPerDay, - PoundPerHour, - PoundPerMinute, - PoundPerSecond, - ShortTonPerHour, - TonnePerDay, - TonnePerHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFluxUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFluxUnit.g.cs deleted file mode 100644 index 2723abf13a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFluxUnit.g.cs +++ /dev/null @@ -1,44 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MassFluxUnit - { - Undefined = 0, - GramPerHourPerSquareCentimeter, - GramPerHourPerSquareMeter, - GramPerHourPerSquareMillimeter, - GramPerSecondPerSquareCentimeter, - GramPerSecondPerSquareMeter, - GramPerSecondPerSquareMillimeter, - KilogramPerHourPerSquareCentimeter, - KilogramPerHourPerSquareMeter, - KilogramPerHourPerSquareMillimeter, - KilogramPerSecondPerSquareCentimeter, - KilogramPerSecondPerSquareMeter, - KilogramPerSecondPerSquareMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFractionUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFractionUnit.g.cs deleted file mode 100644 index 8151a08dfd..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassFractionUnit.g.cs +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MassFractionUnit - { - Undefined = 0, - CentigramPerGram, - CentigramPerKilogram, - DecagramPerGram, - DecagramPerKilogram, - DecigramPerGram, - DecigramPerKilogram, - DecimalFraction, - GramPerGram, - GramPerKilogram, - HectogramPerGram, - HectogramPerKilogram, - KilogramPerGram, - KilogramPerKilogram, - MicrogramPerGram, - MicrogramPerKilogram, - MilligramPerGram, - MilligramPerKilogram, - NanogramPerGram, - NanogramPerKilogram, - PartPerBillion, - PartPerMillion, - PartPerThousand, - PartPerTrillion, - Percent, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs deleted file mode 100644 index 972b52d375..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MassMomentOfInertiaUnit - { - Undefined = 0, - GramSquareCentimeter, - GramSquareDecimeter, - GramSquareMeter, - GramSquareMillimeter, - KilogramSquareCentimeter, - KilogramSquareDecimeter, - KilogramSquareMeter, - KilogramSquareMillimeter, - KilotonneSquareCentimeter, - KilotonneSquareDecimeter, - KilotonneSquareMeter, - KilotonneSquareMilimeter, - MegatonneSquareCentimeter, - MegatonneSquareDecimeter, - MegatonneSquareMeter, - MegatonneSquareMilimeter, - MilligramSquareCentimeter, - MilligramSquareDecimeter, - MilligramSquareMeter, - MilligramSquareMillimeter, - PoundSquareFoot, - PoundSquareInch, - SlugSquareFoot, - SlugSquareInch, - TonneSquareCentimeter, - TonneSquareDecimeter, - TonneSquareMeter, - TonneSquareMilimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassUnit.g.cs deleted file mode 100644 index 37a441d742..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MassUnit.g.cs +++ /dev/null @@ -1,111 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MassUnit - { - Undefined = 0, - Centigram, - Decagram, - Decigram, - - /// - /// Earth mass is a ratio unit to the mass of planet Earth. - /// - /// https://en.wikipedia.org/wiki/Earth_mass - EarthMass, - - /// - /// A grain is a unit of measurement of mass, and in the troy weight, avoirdupois, and Apothecaries' system, equal to exactly 64.79891 milligrams. - /// - /// https://en.wikipedia.org/wiki/Grain_(unit) - Grain, - Gram, - Hectogram, - Kilogram, - Kilopound, - Kilotonne, - - /// - /// The long or imperial hundredweight (abbreviation cwt) is a unit of mass equal to 112 pounds in US and Canada. - /// - /// https://en.wikipedia.org/wiki/Hundredweight - LongHundredweight, - - /// - /// 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. - /// - /// http://en.wikipedia.org/wiki/Long_ton - LongTon, - Megapound, - Megatonne, - Microgram, - Milligram, - Nanogram, - - /// - /// 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). - /// - /// http://en.wikipedia.org/wiki/Ounce - Ounce, - - /// - /// 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. - /// - Pound, - - /// - /// 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". - /// - /// https://en.wikipedia.org/wiki/Hundredweight - ShortHundredweight, - - /// - /// 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. - /// - /// http://en.wikipedia.org/wiki/Short_ton - ShortTon, - - /// - /// 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. - /// - /// http://en.wikipedia.org/wiki/Slug_(unit) - Slug, - - /// - /// Solar mass is a ratio unit to the mass of the solar system star, the sun. - /// - /// https://en.wikipedia.org/wiki/Solar_mass - SolarMass, - - /// - /// 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. - /// - /// http://en.wikipedia.org/wiki/Stone_(unit) - Stone, - Tonne, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarEnergyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarEnergyUnit.g.cs deleted file mode 100644 index cd0ba80e11..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarEnergyUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MolarEnergyUnit - { - Undefined = 0, - JoulePerMole, - KilojoulePerMole, - MegajoulePerMole, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarEntropyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarEntropyUnit.g.cs deleted file mode 100644 index edd5decabe..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarEntropyUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MolarEntropyUnit - { - Undefined = 0, - JoulePerMoleKelvin, - KilojoulePerMoleKelvin, - MegajoulePerMoleKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarMassUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarMassUnit.g.cs deleted file mode 100644 index 2e955277a5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarMassUnit.g.cs +++ /dev/null @@ -1,44 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MolarMassUnit - { - Undefined = 0, - CentigramPerMole, - DecagramPerMole, - DecigramPerMole, - GramPerMole, - HectogramPerMole, - KilogramPerMole, - KilopoundPerMole, - MegapoundPerMole, - MicrogramPerMole, - MilligramPerMole, - NanogramPerMole, - PoundPerMole, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarityUnit.g.cs deleted file mode 100644 index 7eaa326f1c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/MolarityUnit.g.cs +++ /dev/null @@ -1,57 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum MolarityUnit - { - Undefined = 0, - CentimolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - CentimolesPerLiter, - DecimolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - DecimolesPerLiter, - FemtomolePerLiter, - MicromolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - MicromolesPerLiter, - MillimolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - MillimolesPerLiter, - MolePerCubicMeter, - MolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - MolesPerCubicMeter, - [System.Obsolete("Use the singular unit instead.")] - MolesPerLiter, - NanomolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - NanomolesPerLiter, - PicomolePerLiter, - [System.Obsolete("Use the singular unit instead.")] - PicomolesPerLiter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PermeabilityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PermeabilityUnit.g.cs deleted file mode 100644 index 9d236dbc9c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PermeabilityUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PermeabilityUnit - { - Undefined = 0, - HenryPerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PermittivityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PermittivityUnit.g.cs deleted file mode 100644 index 02caf933de..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PermittivityUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PermittivityUnit - { - Undefined = 0, - FaradPerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs deleted file mode 100644 index 3b897930c5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PorousMediumPermeabilityUnit - { - Undefined = 0, - Darcy, - Microdarcy, - Millidarcy, - SquareCentimeter, - SquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerDensityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerDensityUnit.g.cs deleted file mode 100644 index 10946ecb5b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerDensityUnit.g.cs +++ /dev/null @@ -1,76 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PowerDensityUnit - { - Undefined = 0, - DecawattPerCubicFoot, - DecawattPerCubicInch, - DecawattPerCubicMeter, - DecawattPerLiter, - DeciwattPerCubicFoot, - DeciwattPerCubicInch, - DeciwattPerCubicMeter, - DeciwattPerLiter, - GigawattPerCubicFoot, - GigawattPerCubicInch, - GigawattPerCubicMeter, - GigawattPerLiter, - KilowattPerCubicFoot, - KilowattPerCubicInch, - KilowattPerCubicMeter, - KilowattPerLiter, - MegawattPerCubicFoot, - MegawattPerCubicInch, - MegawattPerCubicMeter, - MegawattPerLiter, - MicrowattPerCubicFoot, - MicrowattPerCubicInch, - MicrowattPerCubicMeter, - MicrowattPerLiter, - MilliwattPerCubicFoot, - MilliwattPerCubicInch, - MilliwattPerCubicMeter, - MilliwattPerLiter, - NanowattPerCubicFoot, - NanowattPerCubicInch, - NanowattPerCubicMeter, - NanowattPerLiter, - PicowattPerCubicFoot, - PicowattPerCubicInch, - PicowattPerCubicMeter, - PicowattPerLiter, - TerawattPerCubicFoot, - TerawattPerCubicInch, - TerawattPerCubicMeter, - TerawattPerLiter, - WattPerCubicFoot, - WattPerCubicInch, - WattPerCubicMeter, - WattPerLiter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerRatioUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerRatioUnit.g.cs deleted file mode 100644 index e4a29c66ed..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerRatioUnit.g.cs +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PowerRatioUnit - { - Undefined = 0, - DecibelMilliwatt, - DecibelWatt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerUnit.g.cs deleted file mode 100644 index 4d98f8c28b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PowerUnit.g.cs +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PowerUnit - { - Undefined = 0, - BoilerHorsepower, - BritishThermalUnitPerHour, - Decawatt, - Deciwatt, - ElectricalHorsepower, - Femtowatt, - GigajoulePerHour, - Gigawatt, - HydraulicHorsepower, - JoulePerHour, - KilobritishThermalUnitPerHour, - KilojoulePerHour, - Kilowatt, - MechanicalHorsepower, - MegabritishThermalUnitPerHour, - MegajoulePerHour, - Megawatt, - MetricHorsepower, - Microwatt, - MillijoulePerHour, - Milliwatt, - Nanowatt, - Petawatt, - Picowatt, - Terawatt, - Watt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PressureChangeRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PressureChangeRateUnit.g.cs deleted file mode 100644 index b2e4c0151b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PressureChangeRateUnit.g.cs +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PressureChangeRateUnit - { - Undefined = 0, - AtmospherePerSecond, - KilopascalPerMinute, - KilopascalPerSecond, - KilopoundForcePerSquareInchPerMinute, - KilopoundForcePerSquareInchPerSecond, - MegapascalPerMinute, - MegapascalPerSecond, - MegapoundForcePerSquareInchPerMinute, - MegapoundForcePerSquareInchPerSecond, - MillimeterOfMercuryPerSecond, - PascalPerMinute, - PascalPerSecond, - PoundForcePerSquareInchPerMinute, - PoundForcePerSquareInchPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PressureUnit.g.cs deleted file mode 100644 index f78857c031..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/PressureUnit.g.cs +++ /dev/null @@ -1,79 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum PressureUnit - { - Undefined = 0, - Atmosphere, - Bar, - Centibar, - Decapascal, - Decibar, - DynePerSquareCentimeter, - FootOfElevation, - FootOfHead, - Gigapascal, - Hectopascal, - InchOfMercury, - InchOfWaterColumn, - Kilobar, - KilogramForcePerSquareCentimeter, - KilogramForcePerSquareMeter, - KilogramForcePerSquareMillimeter, - KilonewtonPerSquareCentimeter, - KilonewtonPerSquareMeter, - KilonewtonPerSquareMillimeter, - Kilopascal, - KilopoundForcePerSquareFoot, - KilopoundForcePerSquareInch, - KilopoundForcePerSquareMil, - Megabar, - MeganewtonPerSquareMeter, - Megapascal, - MeterOfElevation, - MeterOfHead, - Microbar, - Micropascal, - Millibar, - MillimeterOfMercury, - MillimeterOfWaterColumn, - Millipascal, - NewtonPerSquareCentimeter, - NewtonPerSquareMeter, - NewtonPerSquareMillimeter, - Pascal, - PoundForcePerSquareFoot, - PoundForcePerSquareInch, - PoundForcePerSquareMil, - PoundPerInchSecondSquared, - TechnicalAtmosphere, - TonneForcePerSquareCentimeter, - TonneForcePerSquareMeter, - TonneForcePerSquareMillimeter, - Torr, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RatioChangeRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RatioChangeRateUnit.g.cs deleted file mode 100644 index bcde32166e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RatioChangeRateUnit.g.cs +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RatioChangeRateUnit - { - Undefined = 0, - DecimalFractionPerSecond, - PercentPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RatioUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RatioUnit.g.cs deleted file mode 100644 index c4d62326dc..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RatioUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RatioUnit - { - Undefined = 0, - DecimalFraction, - PartPerBillion, - PartPerMillion, - PartPerThousand, - PartPerTrillion, - Percent, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReactiveEnergyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReactiveEnergyUnit.g.cs deleted file mode 100644 index 9c5e12ddb0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReactiveEnergyUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ReactiveEnergyUnit - { - Undefined = 0, - KilovoltampereReactiveHour, - MegavoltampereReactiveHour, - VoltampereReactiveHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReactivePowerUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReactivePowerUnit.g.cs deleted file mode 100644 index 6dcb0a2687..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReactivePowerUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ReactivePowerUnit - { - Undefined = 0, - GigavoltampereReactive, - KilovoltampereReactive, - MegavoltampereReactive, - VoltampereReactive, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReciprocalAreaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReciprocalAreaUnit.g.cs deleted file mode 100644 index 822c6e03eb..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReciprocalAreaUnit.g.cs +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ReciprocalAreaUnit - { - Undefined = 0, - InverseSquareCentimeter, - InverseSquareDecimeter, - InverseSquareFoot, - InverseSquareInch, - InverseSquareKilometer, - InverseSquareMeter, - InverseSquareMicrometer, - InverseSquareMile, - InverseSquareMillimeter, - InverseSquareYard, - InverseUsSurveySquareFoot, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReciprocalLengthUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReciprocalLengthUnit.g.cs deleted file mode 100644 index 166f08af87..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ReciprocalLengthUnit.g.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ReciprocalLengthUnit - { - Undefined = 0, - InverseCentimeter, - InverseFoot, - InverseInch, - InverseMeter, - InverseMicroinch, - InverseMil, - InverseMile, - InverseMillimeter, - InverseUsSurveyFoot, - InverseYard, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RelativeHumidityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RelativeHumidityUnit.g.cs deleted file mode 100644 index d1ff2b1726..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RelativeHumidityUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RelativeHumidityUnit - { - Undefined = 0, - Percent, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalAccelerationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalAccelerationUnit.g.cs deleted file mode 100644 index e207d6c1ae..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalAccelerationUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RotationalAccelerationUnit - { - Undefined = 0, - DegreePerSecondSquared, - RadianPerSecondSquared, - RevolutionPerMinutePerSecond, - RevolutionPerSecondSquared, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalSpeedUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalSpeedUnit.g.cs deleted file mode 100644 index 93b644ac7c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalSpeedUnit.g.cs +++ /dev/null @@ -1,45 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RotationalSpeedUnit - { - Undefined = 0, - CentiradianPerSecond, - DeciradianPerSecond, - DegreePerMinute, - DegreePerSecond, - MicrodegreePerSecond, - MicroradianPerSecond, - MillidegreePerSecond, - MilliradianPerSecond, - NanodegreePerSecond, - NanoradianPerSecond, - RadianPerSecond, - RevolutionPerMinute, - RevolutionPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs deleted file mode 100644 index 479001f79c..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RotationalStiffnessPerLengthUnit - { - Undefined = 0, - KilonewtonMeterPerRadianPerMeter, - KilopoundForceFootPerDegreesPerFoot, - MeganewtonMeterPerRadianPerMeter, - NewtonMeterPerRadianPerMeter, - PoundForceFootPerDegreesPerFoot, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalStiffnessUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalStiffnessUnit.g.cs deleted file mode 100644 index 1ca970ecb1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/RotationalStiffnessUnit.g.cs +++ /dev/null @@ -1,65 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum RotationalStiffnessUnit - { - Undefined = 0, - CentinewtonMeterPerDegree, - CentinewtonMillimeterPerDegree, - CentinewtonMillimeterPerRadian, - DecanewtonMeterPerDegree, - DecanewtonMillimeterPerDegree, - DecanewtonMillimeterPerRadian, - DecinewtonMeterPerDegree, - DecinewtonMillimeterPerDegree, - DecinewtonMillimeterPerRadian, - KilonewtonMeterPerDegree, - KilonewtonMeterPerRadian, - KilonewtonMillimeterPerDegree, - KilonewtonMillimeterPerRadian, - KilopoundForceFootPerDegrees, - MeganewtonMeterPerDegree, - MeganewtonMeterPerRadian, - MeganewtonMillimeterPerDegree, - MeganewtonMillimeterPerRadian, - MicronewtonMeterPerDegree, - MicronewtonMillimeterPerDegree, - MicronewtonMillimeterPerRadian, - MillinewtonMeterPerDegree, - MillinewtonMillimeterPerDegree, - MillinewtonMillimeterPerRadian, - NanonewtonMeterPerDegree, - NanonewtonMillimeterPerDegree, - NanonewtonMillimeterPerRadian, - NewtonMeterPerDegree, - NewtonMeterPerRadian, - NewtonMillimeterPerDegree, - NewtonMillimeterPerRadian, - PoundForceFeetPerRadian, - PoundForceFootPerDegrees, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ScalarUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ScalarUnit.g.cs deleted file mode 100644 index 3b0891f314..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ScalarUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ScalarUnit - { - Undefined = 0, - Amount, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SolidAngleUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SolidAngleUnit.g.cs deleted file mode 100644 index 1fa9137298..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SolidAngleUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SolidAngleUnit - { - Undefined = 0, - Steradian, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificEnergyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificEnergyUnit.g.cs deleted file mode 100644 index 1c379e0fb1..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificEnergyUnit.g.cs +++ /dev/null @@ -1,61 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SpecificEnergyUnit - { - Undefined = 0, - BtuPerPound, - CaloriePerGram, - GigawattDayPerKilogram, - GigawattDayPerShortTon, - GigawattDayPerTonne, - GigawattHourPerKilogram, - GigawattHourPerPound, - JoulePerKilogram, - KilocaloriePerGram, - KilojoulePerKilogram, - KilowattDayPerKilogram, - KilowattDayPerShortTon, - KilowattDayPerTonne, - KilowattHourPerKilogram, - KilowattHourPerPound, - MegajoulePerKilogram, - MegawattDayPerKilogram, - MegawattDayPerShortTon, - MegawattDayPerTonne, - MegawattHourPerKilogram, - MegawattHourPerPound, - TerawattDayPerKilogram, - TerawattDayPerShortTon, - TerawattDayPerTonne, - WattDayPerKilogram, - WattDayPerShortTon, - WattDayPerTonne, - WattHourPerKilogram, - WattHourPerPound, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificEntropyUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificEntropyUnit.g.cs deleted file mode 100644 index 744c7608bf..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificEntropyUnit.g.cs +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SpecificEntropyUnit - { - Undefined = 0, - BtuPerPoundFahrenheit, - CaloriePerGramKelvin, - JoulePerKilogramDegreeCelsius, - JoulePerKilogramKelvin, - KilocaloriePerGramKelvin, - KilojoulePerKilogramDegreeCelsius, - KilojoulePerKilogramKelvin, - MegajoulePerKilogramDegreeCelsius, - MegajoulePerKilogramKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs deleted file mode 100644 index f83628860d..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SpecificFuelConsumptionUnit - { - Undefined = 0, - GramPerKiloNewtonSecond, - KilogramPerKilogramForceHour, - KilogramPerKiloNewtonSecond, - PoundMassPerPoundForceHour, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificVolumeUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificVolumeUnit.g.cs deleted file mode 100644 index 64f2e15212..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificVolumeUnit.g.cs +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SpecificVolumeUnit - { - Undefined = 0, - CubicFootPerPound, - CubicMeterPerKilogram, - MillicubicMeterPerKilogram, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificWeightUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificWeightUnit.g.cs deleted file mode 100644 index 21c71caacf..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpecificWeightUnit.g.cs +++ /dev/null @@ -1,49 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SpecificWeightUnit - { - Undefined = 0, - KilogramForcePerCubicCentimeter, - KilogramForcePerCubicMeter, - KilogramForcePerCubicMillimeter, - KilonewtonPerCubicCentimeter, - KilonewtonPerCubicMeter, - KilonewtonPerCubicMillimeter, - KilopoundForcePerCubicFoot, - KilopoundForcePerCubicInch, - MeganewtonPerCubicMeter, - NewtonPerCubicCentimeter, - NewtonPerCubicMeter, - NewtonPerCubicMillimeter, - PoundForcePerCubicFoot, - PoundForcePerCubicInch, - TonneForcePerCubicCentimeter, - TonneForcePerCubicMeter, - TonneForcePerCubicMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpeedUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpeedUnit.g.cs deleted file mode 100644 index a7c8e2659a..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/SpeedUnit.g.cs +++ /dev/null @@ -1,65 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum SpeedUnit - { - Undefined = 0, - CentimeterPerHour, - CentimeterPerMinute, - CentimeterPerSecond, - DecimeterPerMinute, - DecimeterPerSecond, - FootPerHour, - FootPerMinute, - FootPerSecond, - InchPerHour, - InchPerMinute, - InchPerSecond, - KilometerPerHour, - KilometerPerMinute, - KilometerPerSecond, - Knot, - Mach, - MeterPerHour, - MeterPerMinute, - MeterPerSecond, - MicrometerPerMinute, - MicrometerPerSecond, - MilePerHour, - MillimeterPerHour, - MillimeterPerMinute, - MillimeterPerSecond, - NanometerPerMinute, - NanometerPerSecond, - UsSurveyFootPerHour, - UsSurveyFootPerMinute, - UsSurveyFootPerSecond, - YardPerHour, - YardPerMinute, - YardPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs deleted file mode 100644 index 86f6e5d486..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum StandardVolumeFlowUnit - { - Undefined = 0, - StandardCubicCentimeterPerMinute, - StandardCubicFootPerHour, - StandardCubicFootPerMinute, - StandardCubicFootPerSecond, - StandardCubicMeterPerDay, - StandardCubicMeterPerHour, - StandardCubicMeterPerMinute, - StandardCubicMeterPerSecond, - StandardLiterPerMinute, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs deleted file mode 100644 index 1170aab72f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TemperatureChangeRateUnit - { - Undefined = 0, - CentidegreeCelsiusPerSecond, - DecadegreeCelsiusPerSecond, - DecidegreeCelsiusPerSecond, - DegreeCelsiusPerMinute, - DegreeCelsiusPerSecond, - HectodegreeCelsiusPerSecond, - KilodegreeCelsiusPerSecond, - MicrodegreeCelsiusPerSecond, - MillidegreeCelsiusPerSecond, - NanodegreeCelsiusPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureDeltaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureDeltaUnit.g.cs deleted file mode 100644 index 7fded81179..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureDeltaUnit.g.cs +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TemperatureDeltaUnit - { - Undefined = 0, - DegreeCelsius, - DegreeDelisle, - DegreeFahrenheit, - DegreeNewton, - DegreeRankine, - DegreeReaumur, - DegreeRoemer, - Kelvin, - MillidegreeCelsius, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureGradientUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureGradientUnit.g.cs deleted file mode 100644 index 96522d6572..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureGradientUnit.g.cs +++ /dev/null @@ -1,36 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TemperatureGradientUnit - { - Undefined = 0, - DegreeCelsiusPerKilometer, - DegreeCelsiusPerMeter, - DegreeFahrenheitPerFoot, - KelvinPerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureUnit.g.cs deleted file mode 100644 index 9fef394aec..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TemperatureUnit.g.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TemperatureUnit - { - Undefined = 0, - DegreeCelsius, - DegreeDelisle, - DegreeFahrenheit, - DegreeNewton, - DegreeRankine, - DegreeReaumur, - DegreeRoemer, - Kelvin, - MillidegreeCelsius, - SolarTemperature, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ThermalConductivityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ThermalConductivityUnit.g.cs deleted file mode 100644 index b57d36aa6e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ThermalConductivityUnit.g.cs +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ThermalConductivityUnit - { - Undefined = 0, - BtuPerHourFootFahrenheit, - WattPerMeterKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ThermalResistanceUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ThermalResistanceUnit.g.cs deleted file mode 100644 index e2aa2d6d48..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/ThermalResistanceUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ThermalResistanceUnit - { - Undefined = 0, - HourSquareFeetDegreeFahrenheitPerBtu, - SquareCentimeterHourDegreeCelsiusPerKilocalorie, - SquareCentimeterKelvinPerWatt, - SquareMeterDegreeCelsiusPerWatt, - SquareMeterKelvinPerKilowatt, - SquareMeterKelvinPerWatt, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TorquePerLengthUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TorquePerLengthUnit.g.cs deleted file mode 100644 index f400c141d5..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TorquePerLengthUnit.g.cs +++ /dev/null @@ -1,53 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TorquePerLengthUnit - { - Undefined = 0, - KilogramForceCentimeterPerMeter, - KilogramForceMeterPerMeter, - KilogramForceMillimeterPerMeter, - KilonewtonCentimeterPerMeter, - KilonewtonMeterPerMeter, - KilonewtonMillimeterPerMeter, - KilopoundForceFootPerFoot, - KilopoundForceInchPerFoot, - MeganewtonCentimeterPerMeter, - MeganewtonMeterPerMeter, - MeganewtonMillimeterPerMeter, - MegapoundForceFootPerFoot, - MegapoundForceInchPerFoot, - NewtonCentimeterPerMeter, - NewtonMeterPerMeter, - NewtonMillimeterPerMeter, - PoundForceFootPerFoot, - PoundForceInchPerFoot, - TonneForceCentimeterPerMeter, - TonneForceMeterPerMeter, - TonneForceMillimeterPerMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TorqueUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TorqueUnit.g.cs deleted file mode 100644 index cb0b260725..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TorqueUnit.g.cs +++ /dev/null @@ -1,57 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TorqueUnit - { - Undefined = 0, - GramForceCentimeter, - GramForceMeter, - GramForceMillimeter, - KilogramForceCentimeter, - KilogramForceMeter, - KilogramForceMillimeter, - KilonewtonCentimeter, - KilonewtonMeter, - KilonewtonMillimeter, - KilopoundForceFoot, - KilopoundForceInch, - MeganewtonCentimeter, - MeganewtonMeter, - MeganewtonMillimeter, - MegapoundForceFoot, - MegapoundForceInch, - NewtonCentimeter, - NewtonMeter, - NewtonMillimeter, - PoundalFoot, - PoundForceFoot, - PoundForceInch, - TonneForceCentimeter, - TonneForceMeter, - TonneForceMillimeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TurbidityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TurbidityUnit.g.cs deleted file mode 100644 index 8e9c870a04..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/TurbidityUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum TurbidityUnit - { - Undefined = 0, - NTU, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VitaminAUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VitaminAUnit.g.cs deleted file mode 100644 index 566de16722..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VitaminAUnit.g.cs +++ /dev/null @@ -1,33 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VitaminAUnit - { - Undefined = 0, - InternationalUnit, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeConcentrationUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeConcentrationUnit.g.cs deleted file mode 100644 index 5fa899ebe4..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeConcentrationUnit.g.cs +++ /dev/null @@ -1,52 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VolumeConcentrationUnit - { - Undefined = 0, - CentilitersPerLiter, - CentilitersPerMililiter, - DecilitersPerLiter, - DecilitersPerMililiter, - DecimalFraction, - LitersPerLiter, - LitersPerMililiter, - MicrolitersPerLiter, - MicrolitersPerMililiter, - MillilitersPerLiter, - MillilitersPerMililiter, - NanolitersPerLiter, - NanolitersPerMililiter, - PartPerBillion, - PartPerMillion, - PartPerThousand, - PartPerTrillion, - Percent, - PicolitersPerLiter, - PicolitersPerMililiter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs deleted file mode 100644 index 10ea6694f7..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VolumeFlowPerAreaUnit - { - Undefined = 0, - CubicFootPerMinutePerSquareFoot, - CubicMeterPerSecondPerSquareMeter, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeFlowUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeFlowUnit.g.cs deleted file mode 100644 index 0dd4eca79b..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeFlowUnit.g.cs +++ /dev/null @@ -1,94 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VolumeFlowUnit - { - Undefined = 0, - AcreFootPerDay, - AcreFootPerHour, - AcreFootPerMinute, - AcreFootPerSecond, - CentiliterPerDay, - CentiliterPerHour, - CentiliterPerMinute, - CentiliterPerSecond, - CubicCentimeterPerMinute, - CubicDecimeterPerMinute, - CubicFootPerHour, - CubicFootPerMinute, - CubicFootPerSecond, - CubicMeterPerDay, - CubicMeterPerHour, - CubicMeterPerMinute, - CubicMeterPerSecond, - CubicMillimeterPerSecond, - CubicYardPerDay, - CubicYardPerHour, - CubicYardPerMinute, - CubicYardPerSecond, - DeciliterPerDay, - DeciliterPerHour, - DeciliterPerMinute, - DeciliterPerSecond, - KiloliterPerDay, - KiloliterPerHour, - KiloliterPerMinute, - KiloliterPerSecond, - KilousGallonPerMinute, - LiterPerDay, - LiterPerHour, - LiterPerMinute, - LiterPerSecond, - MegaliterPerDay, - MegaukGallonPerSecond, - MicroliterPerDay, - MicroliterPerHour, - MicroliterPerMinute, - MicroliterPerSecond, - MilliliterPerDay, - MilliliterPerHour, - MilliliterPerMinute, - MilliliterPerSecond, - MillionUsGallonsPerDay, - NanoliterPerDay, - NanoliterPerHour, - NanoliterPerMinute, - NanoliterPerSecond, - OilBarrelPerDay, - OilBarrelPerHour, - OilBarrelPerMinute, - OilBarrelPerSecond, - UkGallonPerDay, - UkGallonPerHour, - UkGallonPerMinute, - UkGallonPerSecond, - UsGallonPerDay, - UsGallonPerHour, - UsGallonPerMinute, - UsGallonPerSecond, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumePerLengthUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumePerLengthUnit.g.cs deleted file mode 100644 index 9fe06e5e68..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumePerLengthUnit.g.cs +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VolumePerLengthUnit - { - Undefined = 0, - CubicMeterPerMeter, - CubicYardPerFoot, - CubicYardPerUsSurveyFoot, - LiterPerKilometer, - LiterPerMeter, - LiterPerMillimeter, - OilBarrelPerFoot, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeUnit.g.cs deleted file mode 100644 index ceee64a2f9..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumeUnit.g.cs +++ /dev/null @@ -1,84 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VolumeUnit - { - Undefined = 0, - AcreFoot, - AuTablespoon, - BoardFoot, - Centiliter, - CubicCentimeter, - CubicDecimeter, - CubicFoot, - CubicHectometer, - CubicInch, - CubicKilometer, - CubicMeter, - CubicMicrometer, - CubicMile, - CubicMillimeter, - CubicYard, - Decaliter, - DecausGallon, - Deciliter, - DeciusGallon, - HectocubicFoot, - HectocubicMeter, - Hectoliter, - HectousGallon, - ImperialBeerBarrel, - ImperialGallon, - ImperialOunce, - ImperialPint, - KilocubicFoot, - KilocubicMeter, - KiloimperialGallon, - Kiloliter, - KilousGallon, - Liter, - MegacubicFoot, - MegaimperialGallon, - Megaliter, - MegausGallon, - MetricCup, - MetricTeaspoon, - Microliter, - Milliliter, - OilBarrel, - UkTablespoon, - UsBeerBarrel, - UsCustomaryCup, - UsGallon, - UsLegalCup, - UsOunce, - UsPint, - UsQuart, - UsTablespoon, - UsTeaspoon, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs deleted file mode 100644 index 2f18602337..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum VolumetricHeatCapacityUnit - { - Undefined = 0, - BtuPerCubicFootDegreeFahrenheit, - CaloriePerCubicCentimeterDegreeCelsius, - JoulePerCubicMeterDegreeCelsius, - JoulePerCubicMeterKelvin, - KilocaloriePerCubicCentimeterDegreeCelsius, - KilojoulePerCubicMeterDegreeCelsius, - KilojoulePerCubicMeterKelvin, - MegajoulePerCubicMeterDegreeCelsius, - MegajoulePerCubicMeterKelvin, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs b/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs deleted file mode 100644 index a7e6d93c2e..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum WarpingMomentOfInertiaUnit - { - Undefined = 0, - CentimeterToTheSixth, - DecimeterToTheSixth, - FootToTheSixth, - InchToTheSixth, - MeterToTheSixth, - MillimeterToTheSixth, - } - - #pragma warning restore 1591 -} diff --git a/UnitsNet.WindowsRuntimeComponent/IQuantity.cs b/UnitsNet.WindowsRuntimeComponent/IQuantity.cs deleted file mode 100644 index 51326eed47..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/IQuantity.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// Represents a quantity. - /// - public interface IQuantity - { - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - QuantityType Type { get; } - - /// - /// The of this quantity. - /// - BaseDimensions Dimensions { get; } - - /// - /// Dynamically convert to another unit representation. - /// - /// The unit enum value. The unit must be compatible, so for you should provide a value. - /// Value converted to the specified unit. - /// Wrong unit enum type was given. - double As(object unit); - - /// - /// The unit this quantity was constructed with or the BaseUnit if the default constructor was used. - /// - object Unit { get; } - - /// - /// Get string representation of value and unit. Using two significant digits after radix. - /// - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - string ToString([CanBeNull] string cultureName); - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - string ToString(string cultureName, int significantDigitsAfterRadix); - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to if null. - string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args); - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/InternalHelpers/Guard.cs b/UnitsNet.WindowsRuntimeComponent/InternalHelpers/Guard.cs deleted file mode 100644 index 0c4f48ce27..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/InternalHelpers/Guard.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed under MIT 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 JetBrains.Annotations; - -namespace UnitsNet.InternalHelpers -{ - /// - /// Guard methods to ensure parameter values satisfy pre-conditions and use a consistent exception message. - /// - internal static class Guard - { - /// - /// Throws if value is , - /// or . - /// - /// The value to check. - /// Name of parameter in calling method. - /// The given if valid. - /// If is invalid. - internal static double EnsureValidNumber(double value, [InvokerParameterName] 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.WindowsRuntimeComponent/InternalHelpers/ReflectionBridgeExtensions.cs b/UnitsNet.WindowsRuntimeComponent/InternalHelpers/ReflectionBridgeExtensions.cs deleted file mode 100644 index f5a9341450..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/InternalHelpers/ReflectionBridgeExtensions.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Licensed under MIT 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.Reflection; -using System.Runtime.CompilerServices; -#if NET40 || NET35 || NET20 || SILVERLIGHT -using UniformTypeInfo = System.Type; -#else -using UniformTypeInfo = System.Reflection.TypeInfo; -#endif - -[assembly: - InternalsVisibleTo( - "UnitsNet.Serialization.JsonNet, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] - -// Based on -// https://github.com/StefH/ReflectionBridge/blob/c1e34e57fe3fc93507e83d5cebc1677396645397/ReflectionBridge/src/ReflectionBridge/Extensions/ReflectionBridgeExtensions.cs -// MIT license -namespace UnitsNet.InternalHelpers -{ - internal struct TypeWrapper - { - private readonly Type _type; - - public TypeWrapper(Type type) - { - _type = type; - } - - internal Assembly Assembly => _type.ToUniformType().Assembly; - internal bool IsEnum => _type.ToUniformType().IsEnum; - internal bool IsClass => _type.ToUniformType().IsClass; - internal bool IsAssignableFrom(Type other) => _type.ToUniformType().IsAssignableFrom(other.ToUniformType()); - internal bool IsValueType => _type.ToUniformType().IsValueType; - - internal PropertyInfo GetProperty(string name) - { -#if NET40 || NET35 || NET20 || SILVERLIGHT - return _type.GetProperty(name); -#else - return _type.GetTypeInfo().GetDeclaredProperty(name); -#endif - } - - internal IEnumerable GetDeclaredMethods() - { - var t = _type.ToUniformType(); - while (t != null) - { -#if NET40 || NET35 || NET20 || SILVERLIGHT - foreach (MethodInfo m in t.GetMethods()) -#else - foreach (MethodInfo m in t.DeclaredMethods) -#endif - yield return m; - - t = t.BaseType?.ToUniformType(); - } - } - } - - internal static class ReflectionBridgeExtensions - { - /// - /// Wrap the type to make it .NET agnostic using Type for old targets and the newer TypeInfo for newer targets. - /// - public static TypeWrapper Wrap(this Type type) - { - return new TypeWrapper(type); - } - - /// - /// Returns the type or type info object depending on compile target, such as TypeInfo for .NET 4.5+ and Type for .NET - /// 4.0 and older. - /// The APIs of these two objects are similar, but obtaining them is slightly different. - /// The idea is to get fewer #if pragma statements in the code. - /// - public static UniformTypeInfo ToUniformType(this Type type) - { -#if NET40 || NET35 || NET20 || SILVERLIGHT - return type; -#else - return type.GetTypeInfo(); -#endif - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/Properties/AssemblyInfo.cs b/UnitsNet.WindowsRuntimeComponent/Properties/AssemblyInfo.cs deleted file mode 100644 index 2f46d9f853..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed under MIT 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.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; - -using System.Runtime.InteropServices; -[assembly: ComVisible(false)] - -[assembly: AssemblyTitle("Units.NET")] -[assembly: AssemblyDescription("Units.NET gives you all the common units of measurement and the conversions between them. It is light-weight, unit tested and supports PCL.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Andreas Gullberg Larsen")] -[assembly: AssemblyProduct("Units.NET")] -[assembly: AssemblyCopyright("Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("")] -[assembly: AssemblyVersion("4.149.0")] -[assembly: AssemblyFileVersion("4.149.0")] -[assembly: InternalsVisibleTo("UnitsNet.WindowsRuntimeComponent.Tests")] diff --git a/UnitsNet.WindowsRuntimeComponent/QuantityInfo.cs b/UnitsNet.WindowsRuntimeComponent/QuantityInfo.cs deleted file mode 100644 index 874d8dfb16..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/QuantityInfo.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Licensed under MIT 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 System.Reflection; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// 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. - /// - /// - /// Typically you obtain this by looking it up via quantities, like or . - /// - internal class QuantityInfo - { - private static readonly string UnitEnumNamespace = typeof(LengthUnit).Namespace; - - private static readonly Type[] UnitEnumTypes = typeof(Length) - .Wrap() - .Assembly - .GetExportedTypes() - .Where(t => t.Wrap().IsEnum && t.Namespace == UnitEnumNamespace && t.Name.EndsWith("Unit")) - .ToArray(); - - public QuantityInfo(QuantityType quantityType, [NotNull] Enum[] units, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, [NotNull] BaseDimensions baseDimensions) - { - if(quantityType == QuantityType.Undefined) throw new ArgumentException("Quantity type can not be undefined.", nameof(quantityType)); - if(units == null) throw new ArgumentNullException(nameof(units)); - if(baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); - if(zero == null) throw new ArgumentNullException(nameof(zero)); - if(baseDimensions == null) throw new ArgumentNullException(nameof(baseDimensions)); - - Name = quantityType.ToString(); - QuantityType = quantityType; - UnitType = UnitEnumTypes.First(t => t.Name == $"{quantityType}Unit"); - UnitInfos = units.Select(unit => new UnitInfo(unit)).ToArray(); - UnitNames = UnitInfos.Select(unitInfo => unitInfo.Name).ToArray(); - Units = units; - BaseUnitInfo = new UnitInfo(baseUnit); - BaseUnit = BaseUnitInfo.Value; - Zero = zero; - ValueType = zero.GetType(); - BaseDimensions = baseDimensions; - } - - /// - /// Quantity name, such as "Length" or "Mass". - /// - public string Name { get; } - - /// - /// Quantity type, such as or . - /// - public QuantityType QuantityType { get; } - - public UnitInfo[] UnitInfos { get; } - - /// - /// All unit names for the quantity, such as ["Centimeter", "Decimeter", "Meter", ...]. - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the UnitInfos property.")] - public string[] UnitNames { get; } - - /// - /// All unit enum values for the quantity, such as [, - /// , , ...]. - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the UnitInfos property.")] - public Enum[] Units { get; } - - public UnitInfo BaseUnitInfo { get; } - - /// - /// The base unit for the quantity, such as . - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the BaseUnitInfo property.")] - public Enum BaseUnit { get; } - - /// - /// Zero value of quantity, such as . - /// - public IQuantity Zero { get; } - - /// - /// Unit enum type, such as or . - /// - public Type UnitType { get; } - - /// - /// Quantity value type, such as or . - /// - public Type ValueType { get; } - - /// - /// The for a quantity. - /// - public BaseDimensions BaseDimensions { get; } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/QuantityNotFoundException.cs b/UnitsNet.WindowsRuntimeComponent/QuantityNotFoundException.cs deleted file mode 100644 index 4e288edb04..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/QuantityNotFoundException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed under MIT 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 -{ - /// - /// Quantity type was not found. This is typically thrown for dynamic conversions, - /// such as . - /// - internal class QuantityNotFoundException : UnitsNetException - { - public QuantityNotFoundException() - { - } - - public QuantityNotFoundException(string message) : base(message) - { - } - - public QuantityNotFoundException(string message, Exception innerException) : base(message, innerException) - { - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/UnitConverter.cs b/UnitsNet.WindowsRuntimeComponent/UnitConverter.cs deleted file mode 100644 index 6a06da69cb..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitConverter.cs +++ /dev/null @@ -1,422 +0,0 @@ -// Licensed under MIT 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; -using System.Reflection; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// Convert between units of a quantity, such as converting from meters to centimeters of a given length. - /// - [PublicAPI] - public static class UnitConverter - { - private static readonly string UnitTypeNamespace = typeof(LengthUnit).Namespace; - private static readonly Assembly UnitsNetAssembly = typeof(Length).Wrap().Assembly; - - private static readonly Type[] QuantityTypes = UnitsNetAssembly.GetTypes() - .Where(typeof(IQuantity).Wrap().IsAssignableFrom) - .Where(x => x.Wrap().IsClass || x.Wrap().IsValueType) // Future-proofing: we are discussing changing quantities from struct to class - .ToArray(); - - private static readonly Type[] UnitTypes = UnitsNetAssembly.GetTypes() - .Where(x => x.Namespace == UnitTypeNamespace && x.Wrap().IsEnum && x.Name.EndsWith("Unit")) - .ToArray(); - - /// - /// Convert between any two quantity units given a numeric value and two unit enum values. - /// - /// Numeric value. - /// From unit enum value. - /// To unit enum value, must be compatible with . - /// The converted value in the new unit representation. - internal static double Convert(double fromValue, Enum fromUnitValue, Enum toUnitValue) - { - return Quantity - .From(fromValue, fromUnitValue) - .As(toUnitValue); - } - - /// - /// Try to convert between any two quantity units given a numeric value and two unit enum values. - /// - /// Numeric value. - /// From unit enum value. - /// To unit enum value, must be compatible with . - /// The converted value, if successful. Otherwise default. - /// True if successful. - internal static bool TryConvert(double fromValue, Enum fromUnitValue, Enum toUnitValue, out double convertedValue) - { - convertedValue = 0; - if (!Quantity.TryFrom(fromValue, fromUnitValue, out IQuantity from)) return false; - - try - { - // We're not going to implement TryAs() in all quantities, so let's just try-catch here - convertedValue = from.As(toUnitValue); - return true; - } - catch - { - return false; - } - } - - /// - /// 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 - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// - /// Name of quantity, such as "Length" and "Mass". for all - /// values. - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// double centimeters = ConvertByName(5, "Length", "Meter", "Centimeter"); // 500 - /// Output value as the result of converting to . - /// No quantities were found that match . - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - public static double ConvertByName(double 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); - } - - /// - /// 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 - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// - /// Name of quantity, such as "Length" and "Mass". for all - /// values. - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// Result if conversion was successful, 0 if not. - /// bool ok = TryConvertByName(5, "Length", "Meter", "Centimeter", out double centimeters); // 500 - /// True if conversion was successful. - public static bool TryConvertByName(double inputValue, string quantityName, string fromUnit, string toUnit, out double result) - { - result = 0d; - - if (!TryGetUnitType(quantityName, out var unitType)) - return false; - - if (!TryParseUnit(unitType, fromUnit, out var fromUnitValue)) // ex: LengthUnit.Meter - return false; - - if (!TryParseUnit(unitType, toUnit, out var toUnitValue)) // ex: LengthUnit.Centimeter - return false; - - result = Convert(inputValue, fromUnitValue, toUnitValue); - return true; - } - - /// - /// 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 - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// - /// Name of quantity, such as "Length" and "Mass". for all - /// values. - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// Output value as the result of converting to . - public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) - { - // WindowsRuntimeComponent does not support default values on public methods - // ReSharper disable once IntroduceOptionalParameters.Global - return ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, null); - } - - /// - /// 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 - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// - /// Name of quantity, such as "Length" and "Mass". for all - /// values. - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// Culture to parse abbreviations with. - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// Output value as the result of converting to . - /// No quantity types match the . - /// - /// No unit types match the prefix of or no units - /// are mapped to the abbreviation. - /// - /// More than one unit matches the abbreviation. - public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string culture) - { - if (!TryGetQuantityType(quantityName, out var quantityType)) - throw new QuantityNotFoundException($"The given quantity name was not found: {quantityName}"); - - if (!TryGetUnitType(quantityName, out var unitType)) - throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); - - var cultureInfo = string.IsNullOrWhiteSpace(culture) ? GlobalConfiguration.DefaultCulture : new CultureInfo(culture); - - var fromUnitValue = UnitParser.Default.Parse(fromUnitAbbrev, unitType, cultureInfo); // ex: ("m", LengthUnit) => LengthUnit.Meter - var toUnitValue = UnitParser.Default.Parse(toUnitAbbrev, unitType, cultureInfo); // ex:("cm", LengthUnit) => LengthUnit.Centimeter - - var fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) - var fromResult = fromMethod.Invoke(null, new object[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter) - - var asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit) - var asResult = asMethod.Invoke(fromResult, new object[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) - - return (double) asResult; - } - - /// - /// 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 - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// - /// Name of quantity, such as "Length" and "Mass". for all - /// values. - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// Result if conversion was successful, 0 if not. - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// True if conversion was successful. - public static bool TryConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result) - { - return TryConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result, null); - } - - /// - /// 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 - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// - /// Name of quantity, such as "Length" and "Mass". for all - /// values. - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// - /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as - /// . - /// - /// Culture to parse abbreviations with. - /// Result if conversion was successful, 0 if not. - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// True if conversion was successful. - public static bool TryConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result, - string culture) - { - result = 0d; - - if (!TryGetQuantityType(quantityName, out var quantityType)) - return false; - - if (!TryGetUnitType(quantityName, out var unitType)) - return false; - - var cultureInfo = string.IsNullOrWhiteSpace(culture) ? GlobalConfiguration.DefaultCulture : new CultureInfo(culture); - - if (!UnitParser.Default.TryParse(fromUnitAbbrev, unitType, cultureInfo, out var fromUnitValue)) // ex: ("m", LengthUnit) => LengthUnit.Meter - return false; - - if (!UnitParser.Default.TryParse(toUnitAbbrev, unitType, cultureInfo, out var toUnitValue)) // ex:("cm", LengthUnit) => LengthUnit.Centimeter - return false; - - var fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) - var fromResult = fromMethod.Invoke(null, new object[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter) - - var asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit) - var asResult = asMethod.Invoke(fromResult, new object[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter) - - result = (double) asResult; - return true; - } - - private static MethodInfo GetAsMethod(Type quantityType, Type unitType) - { - // Only a single As() method as of this writing, but let's safe-guard a bit for future-proofing - // ex: double result = quantity.As(LengthUnit outputUnit); - return quantityType.Wrap().GetDeclaredMethods() - .Single(m => m.Name == "As" && - !m.IsStatic && - m.IsPublic && - HasParameterTypes(m, unitType) && - m.ReturnType == typeof(double)); - } - - private static MethodInfo GetStaticFromMethod(Type quantityType, Type unitType) - { - // Want to match: Length l = UnitsNet.Length.From(double inputValue, LengthUnit inputUnit) - // Do NOT match : Length? UnitsNet.Length.From(double? inputValue, LengthUnit inputUnit) - return quantityType.Wrap().GetDeclaredMethods() - .Single(m => m.Name == "From" && - m.IsStatic && - m.IsPublic && - HasParameterTypes(m, typeof(double), unitType) && - m.ReturnType == quantityType); - } - - private static bool HasParameterTypes(MethodInfo methodInfo, params Type[] expectedTypes) - { - var parameters = methodInfo.GetParameters(); - if (parameters.Length != expectedTypes.Length) - throw new ArgumentException($"The number of parameters {parameters.Length} did not match the number of types {expectedTypes.Length}."); - - for (var i = 0; i < parameters.Length; i++) - { - var p = parameters[i]; - var t = expectedTypes[i]; - if (p.ParameterType != t) - return false; - } - - return true; - } - - - /// - /// Parse a unit by the unit enum type and a unit enum value > - /// - /// Unit type, such as . - /// Unit name, such as "Meter" corresponding to . - /// The return enum value, such as boxed as an object. - /// True if succeeded, otherwise false. - /// No unit values match the . - private static bool TryParseUnit(Type unitType, string unitName, out Enum unitValue) - { - unitValue = null; - var eNames = Enum.GetNames(unitType); - unitName = eNames.FirstOrDefault(x => x.Equals(unitName, StringComparison.OrdinalIgnoreCase)); - if (unitName == null) - return false; - - unitValue = (Enum) Enum.Parse(unitType, unitName); - return true; - } - - private static bool TryGetUnitType(string quantityName, out Type unitType) - { - var unitTypeName = quantityName + "Unit"; // ex. LengthUnit - - unitType = UnitTypes.FirstOrDefault(x => - x.Name.Equals(unitTypeName, StringComparison.OrdinalIgnoreCase)); - - return unitType != null; - } - - private static bool TryGetQuantityType(string quantityName, out Type quantityType) - { - quantityType = QuantityTypes.FirstOrDefault(x => x.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); - - return quantityType != null; - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/UnitFormatter.cs b/UnitsNet.WindowsRuntimeComponent/UnitFormatter.cs deleted file mode 100644 index 3e1259b718..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitFormatter.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Licensed under MIT 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; -using JetBrains.Annotations; - -namespace UnitsNet -{ - /// - /// Utility class for formatting units and values. - /// - internal static class UnitFormatter - { - /// - /// Gets the default ToString format for the specified value. - /// - /// The value to format. - /// - /// The number of digits after the radix point to display in the formatted - /// string. - /// - /// A ToString format for the specified value. - 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; - } - - /// - /// Gets ToString format arguments. - /// - /// The type of units to format. - /// The units - /// The unit value to format. - /// The current culture. - /// The list of format arguments. - /// An array of ToString format arguments. - public static object[] GetFormatArgs(TUnitType unit, double value, [CanBeNull] IFormatProvider culture, IEnumerable 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.WindowsRuntimeComponent/UnitInfo.cs b/UnitsNet.WindowsRuntimeComponent/UnitInfo.cs deleted file mode 100644 index 9ca2c85e89..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using UnitsNet.Units; - -namespace UnitsNet -{ - /// - /// 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. - /// - /// - /// Typically you obtain this by looking it up via . - /// - internal class UnitInfo - { - public UnitInfo(Enum value) - { - Value = value; - Name = value.ToString(); - } - - /// - /// The enum value of the unit, such as [, - /// , , ...]. - /// - public Enum Value; - - /// - /// The name of the unit, such as ["Centimeter", "Decimeter", "Meter", ...]. - /// - public string Name { get; } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/UnitNotFoundException.cs b/UnitsNet.WindowsRuntimeComponent/UnitNotFoundException.cs deleted file mode 100644 index 9469b77172..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitNotFoundException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed under MIT 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 -{ - /// - /// Unit was not found. This is typically thrown for dynamic conversions, - /// such as . - /// - internal class UnitNotFoundException : UnitsNetException - { - public UnitNotFoundException() - { - } - - public UnitNotFoundException(string message) : base(message) - { - } - - public UnitNotFoundException(string message, Exception innerException) : base(message, innerException) - { - } - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/UnitSystem.cs b/UnitsNet.WindowsRuntimeComponent/UnitSystem.cs deleted file mode 100644 index c116359e7f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitSystem.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; -using UnitsNet.Units; - -namespace UnitsNet -{ - public sealed class UnitSystem - { - /// - /// Creates an instance of a unit system with the specified base units. - /// - /// The base units for the unit system. - public UnitSystem(BaseUnits baseUnits) - { - if(baseUnits is null) - throw new ArgumentNullException(nameof(baseUnits)); - - if(baseUnits.Length == LengthUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - if(baseUnits.Mass == MassUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - if(baseUnits.Time == DurationUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - if(baseUnits.Current == ElectricCurrentUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - if(baseUnits.Temperature == TemperatureUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - if(baseUnits.Amount == AmountOfSubstanceUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - if(baseUnits.LuminousIntensity == LuminousIntensityUnit.Undefined) - throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - - BaseUnits = baseUnits; - } - - /// - public override bool Equals(object obj) - { - if(obj is null || !(obj is UnitSystem)) - return false; - - return Equals((UnitSystem)obj); - } - - [Windows.Foundation.Metadata.DefaultOverload] - public bool Equals(UnitSystem other) - { - if(other is null) - return false; - - return BaseUnits.Equals(other.BaseUnits); - } - - /// - public override int GetHashCode() - { - return new {BaseUnits}.GetHashCode(); - } - - 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); - - /// - /// Gets the SI unit system. - /// - public static UnitSystem SI{ get; } = new UnitSystem(SIBaseUnits); - } -} diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj deleted file mode 100644 index ce4686a21f..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj +++ /dev/null @@ -1,141 +0,0 @@ - - - - - Debug - AnyCPU - {2DA428CA-BFE1-43FA-86D2-7CB42289D596} - winmdobj - Properties - UnitsNet - UnitsNet - en-US - UAP - 10.0.16299.0 - 10.0.10586.0 - 14 - 512 - {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - false - ..\Artifacts\UnitsNet.WindowsRuntimeComponent - 7.3 - - - - CS0618;CS1591 - - - true - true - $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - - - - AnyCPU - true - full - false - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - prompt - 4 - - - AnyCPU - pdbonly - true - TRACE;NETFX_CORE;WINDOWS_UWP - prompt - 4 - true - ..\Artifacts\UnitsNet.WindowsRuntimeComponent\UnitsNet.XML - - - x86 - true - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - full - x86 - false - prompt - - - x86 - TRACE;NETFX_CORE;WINDOWS_UWP - true - pdbonly - x86 - false - prompt - - - ARM - true - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - full - ARM - false - prompt - - - ARM - TRACE;NETFX_CORE;WINDOWS_UWP - true - pdbonly - ARM - false - prompt - - - x64 - true - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - full - x64 - false - prompt - - - x64 - TRACE;NETFX_CORE;WINDOWS_UWP - true - pdbonly - x64 - false - prompt - - - PackageReference - - - - - - - Common\%(RecursiveDir)%(Filename)%(Extension) - - - - - 6.0.6 - - - 11.1.0 - - - - 4.5.0 - - - - - 14.0 - - - - diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj.DotSettings b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj.DotSettings deleted file mode 100644 index 0b0edaecd0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.csproj.DotSettings +++ /dev/null @@ -1,2 +0,0 @@ - - True \ No newline at end of file diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec b/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec deleted file mode 100644 index 8d1101fce0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNet.WindowsRuntimeComponent.nuspec +++ /dev/null @@ -1,25 +0,0 @@ - - - - UnitsNet.WindowsRuntimeComponent - 4.149.0 - Units.NET - Windows Runtime Component - Andreas Gullberg Larsen - Andreas Gullberg Larsen - MIT - https://github.com/angularsen/UnitsNet - false - For C#/VB Universal Windows code (UWP), use UnitsNet instead. This is a Windows Runtime Component with reduced functionality to support all UWP languages, such as JavaScript and C++, and other runtime components. - For C#/VB Universal Windows code (UWP), use UnitsNet instead. - https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png - - - Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). - en-US - unit units measurement si metric imperial abbreviation abbreviations convert conversion parse c# .net immutable uwp uap winrt win10 windows runtime component - - - - - - diff --git a/UnitsNet.WindowsRuntimeComponent/UnitsNetException.cs b/UnitsNet.WindowsRuntimeComponent/UnitsNetException.cs deleted file mode 100644 index 380601c549..0000000000 --- a/UnitsNet.WindowsRuntimeComponent/UnitsNetException.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed under MIT 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 -{ - internal class UnitsNetException : Exception - { - public UnitsNetException() - { - HResult = 1; - } - - public UnitsNetException(string message) : base(message) - { - HResult = 1; - } - - public UnitsNetException(string message, Exception innerException) : base(message, innerException) - { - HResult = 1; - } - } -} diff --git a/UnitsNet.sln b/UnitsNet.sln index 4e089aca8d..6a9d558b59 100644 --- a/UnitsNet.sln +++ b/UnitsNet.sln @@ -11,8 +11,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.Json EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Tests", "UnitsNet.Tests\UnitsNet.Tests.csproj", "{0E3B7567-5DF2-44BD-88DB-CCF050D3F943}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Serialization.JsonNet.CompatibilityTests", "UnitsNet.Serialization.JsonNet.CompatibilityTests\UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj", "{21F2FFAC-BF39-487F-9ADE-37100162F955}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.Benchmark", "UnitsNet.Benchmark\UnitsNet.Benchmark.csproj", "{76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeGen", "CodeGen\CodeGen.csproj", "{078E3D44-4F60-46B3-9099-91A7CBF0B213}" @@ -28,7 +26,7 @@ ProjectSection(SolutionItems) = preProject .gitignore = .gitignore appveyor.yml = appveyor.yml build.bat = build.bat - build-with-wrc.bat = build-with-wrc.bat + build-all-targets.bat = build-all-targets.bat clean.bat = clean.bat CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md CONTRIBUTING.md = CONTRIBUTING.md @@ -66,10 +64,6 @@ Global {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Debug|Any CPU.Build.0 = Debug|Any CPU {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|Any CPU.ActiveCfg = Release|Any CPU {0E3B7567-5DF2-44BD-88DB-CCF050D3F943}.Release|Any CPU.Build.0 = Release|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21F2FFAC-BF39-487F-9ADE-37100162F955}.Release|Any CPU.Build.0 = Release|Any CPU {76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}.Debug|Any CPU.Build.0 = Debug|Any CPU {76B9C7C8-E3D3-4FA7-B782-78E4BA1D0AD8}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/UnitsNet/BaseDimensions.cs b/UnitsNet/BaseDimensions.cs index 295ac84b34..92a1fc1b3e 100644 --- a/UnitsNet/BaseDimensions.cs +++ b/UnitsNet/BaseDimensions.cs @@ -30,7 +30,7 @@ public BaseDimensions(int length, int mass, int time, int current, int temperatu /// True if the dimensions represent a base quantity, otherwise false. public bool IsBaseQuantity() { - var dimensionsArray = new int[]{Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}; + var dimensionsArray = new[] { Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity }; bool onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1; return onlyOneEqualsOne; } @@ -54,20 +54,18 @@ public bool IsDimensionless() } /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { - if (obj is null || !(obj is BaseDimensions)) + if (obj is not BaseDimensions other) return false; - var other = (BaseDimensions)obj; - return Length == other.Length && - Mass == other.Mass && - Time == other.Time && - Current == other.Current && - Temperature == other.Temperature && - Amount == other.Amount && - LuminousIntensity == other.LuminousIntensity; + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; } /// @@ -83,7 +81,7 @@ public override int GetHashCode() /// Resulting dimensions. public BaseDimensions Multiply(BaseDimensions right) { - if (right is null) + if(right is null) throw new ArgumentNullException(nameof(right)); return new BaseDimensions( @@ -103,7 +101,7 @@ public BaseDimensions Multiply(BaseDimensions right) /// Resulting dimensions. public BaseDimensions Divide(BaseDimensions right) { - if (right is null) + if(right is null) throw new ArgumentNullException(nameof(right)); return new BaseDimensions( @@ -122,9 +120,9 @@ public BaseDimensions Divide(BaseDimensions right) /// Left. /// Right. /// True if equal. - public static bool operator ==(BaseDimensions left, BaseDimensions right) + public static bool operator ==(BaseDimensions? left, BaseDimensions? right) { - return left is null ? right is null : left.Equals(right); + return left?.Equals(right!) ?? right is null; } /// @@ -146,10 +144,8 @@ public BaseDimensions Divide(BaseDimensions right) /// Resulting dimensions. public static BaseDimensions operator *(BaseDimensions left, BaseDimensions right) { - if (left is null) - throw new ArgumentNullException(nameof(left)); - else if (right is null) - throw new ArgumentNullException(nameof(right)); + if (left is null) throw new ArgumentNullException(nameof(left)); + if (right is null) throw new ArgumentNullException(nameof(right)); return left.Multiply(right); } @@ -162,10 +158,8 @@ public BaseDimensions Divide(BaseDimensions right) /// Resulting dimensions. public static BaseDimensions operator /(BaseDimensions left, BaseDimensions right) { - if (left is null) - throw new ArgumentNullException(nameof(left)); - else if (right is null) - throw new ArgumentNullException(nameof(right)); + if (left is null) throw new ArgumentNullException(nameof(left)); + if (right is null) throw new ArgumentNullException(nameof(right)); return left.Divide(right); } @@ -190,11 +184,11 @@ private static void AppendDimensionString(StringBuilder sb, string name, int val { var absoluteValue = Math.Abs(value); - if (absoluteValue > 0) + if(absoluteValue > 0) { sb.AppendFormat("[{0}]", name); - if (absoluteValue > 1) + if(absoluteValue > 1) sb.AppendFormat("^{0}", value); } } diff --git a/UnitsNet/BaseUnits.cs b/UnitsNet/BaseUnits.cs index cafc37e7c0..89858ddb40 100644 --- a/UnitsNet/BaseUnits.cs +++ b/UnitsNet/BaseUnits.cs @@ -31,13 +31,13 @@ public sealed class BaseUnits: IEquatable /// The amount of substance unit (N). /// The luminous intensity unit (J). public BaseUnits( - LengthUnit length = LengthUnit.Undefined, - MassUnit mass = MassUnit.Undefined, - DurationUnit time = DurationUnit.Undefined, - ElectricCurrentUnit current = ElectricCurrentUnit.Undefined, - TemperatureUnit temperature = TemperatureUnit.Undefined, - AmountOfSubstanceUnit amount = AmountOfSubstanceUnit.Undefined, - LuminousIntensityUnit luminousIntensity = LuminousIntensityUnit.Undefined) + LengthUnit? length = null, + MassUnit? mass = null, + DurationUnit? time = null, + ElectricCurrentUnit? current = null, + TemperatureUnit? temperature = null, + AmountOfSubstanceUnit? amount = null, + LuminousIntensityUnit? luminousIntensity = null) { Length = length; Mass = mass; @@ -47,22 +47,19 @@ public BaseUnits( Amount = amount; LuminousIntensity = luminousIntensity; - IsFullyDefined = Length != LengthUnit.Undefined && - Mass != MassUnit.Undefined && - Time != DurationUnit.Undefined && - Current != ElectricCurrentUnit.Undefined && - Temperature != TemperatureUnit.Undefined && - Amount != AmountOfSubstanceUnit.Undefined && - LuminousIntensity != LuminousIntensityUnit.Undefined; + 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; } /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { - if (obj is null || !(obj is BaseUnits)) - return false; - - return Equals((BaseUnits)obj); + return obj is BaseUnits other && Equals(other); } /// @@ -70,7 +67,7 @@ public override bool Equals(object obj) /// /// The other instance to check if equal to. /// True if equal, otherwise false. - public bool Equals(BaseUnits other) + public bool Equals(BaseUnits? other) { if (other is null) return false; @@ -93,20 +90,19 @@ public bool Equals(BaseUnits other) /// True if the base units are a subset of other, otherwise false. public bool IsSubsetOf(BaseUnits other) { - if (other is null) - return false; + 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 == LengthUnit.Undefined || Length == other.Length) && - (Mass == MassUnit.Undefined || Mass == other.Mass) && - (Time == DurationUnit.Undefined || Time == other.Time) && - (Current == ElectricCurrentUnit.Undefined || Current == other.Current) && - (Temperature == TemperatureUnit.Undefined || Temperature == other.Temperature) && - (Amount == AmountOfSubstanceUnit.Undefined || Amount == other.Amount) && - (LuminousIntensity == LuminousIntensityUnit.Undefined || LuminousIntensity == other.LuminousIntensity); + 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); } /// @@ -122,9 +118,9 @@ public override int GetHashCode() /// The right instance. /// True if equal, otherwise false. /// - public static bool operator ==(BaseUnits left, BaseUnits right) + public static bool operator ==(BaseUnits? left, BaseUnits? right) { - return left is null ? right is null : left.Equals(right); + return left?.Equals(right!) ?? right is null; } /// @@ -144,13 +140,17 @@ public override string ToString() { var sb = new StringBuilder(); - sb.AppendFormat("[Length]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Length)); - sb.AppendFormat("[Mass]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Mass)); - sb.AppendFormat("[Time]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Time)); - sb.AppendFormat("[Current]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Current)); - sb.AppendFormat("[Temperature]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Temperature)); - sb.AppendFormat("[Amount]: {0}, ", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(Amount)); - sb.AppendFormat("[LuminousIntensity]: {0}", UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LuminousIntensity)); + string GetDefaultAbbreviation(TUnitType? unitOrNull) where TUnitType : struct, Enum => 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(); } @@ -158,37 +158,37 @@ public override string ToString() /// /// Gets the length unit (L). /// - public LengthUnit Length { get; } + public LengthUnit? Length { get; } /// /// Gets the mass unit (M). /// - public MassUnit Mass{ get; } + public MassUnit? Mass{ get; } /// /// Gets the time unit (T). /// - public DurationUnit Time{ get; } + public DurationUnit? Time{ get; } /// /// Gets the electric current unit (I). /// - public ElectricCurrentUnit Current{ get; } + public ElectricCurrentUnit? Current{ get; } /// /// Gets the temperature unit (Θ). /// - public TemperatureUnit Temperature{ get; } + public TemperatureUnit? Temperature{ get; } /// /// Gets the amount of substance unit (N). /// - public AmountOfSubstanceUnit Amount{ get; } + public AmountOfSubstanceUnit? Amount{ get; } /// /// Gets the luminous intensity unit (J). /// - public LuminousIntensityUnit LuminousIntensity{ get; } + public LuminousIntensityUnit? LuminousIntensity{ get; } /// /// Gets whether or not all of the base units are defined. diff --git a/UnitsNet/Comparison.cs b/UnitsNet/Comparison.cs index 575707e6b5..ac6726c3e2 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -65,6 +65,61 @@ public static bool Equals(double referenceValue, double otherValue, double toler } } + /// + /// + /// Checks if two values are equal with a given relative or absolute tolerance. + /// + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a percentage of . A relative tolerance of + /// 0.01 means the + /// absolute difference of and must be within +/- + /// 1%. + /// + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// + /// Equals(a, b, 0.01, ComparisonType.Relative); + /// + /// + /// + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a fixed number. + /// + /// In this example, the two values will be equal if abs( - + /// ) <= 0.01 + /// + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// + /// The reference value. If using relative tolerance, it is the value which the relative + /// tolerance will be calculated against. + /// + /// The value to compare to. + /// The absolute or relative tolerance value. Must be greater than or equal to 0. + /// Whether the tolerance is absolute or relative. + /// + 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."); + } + } + /// /// Checks if two values are equal with a given relative tolerance. /// @@ -95,6 +150,36 @@ public static bool EqualsRelative(double referenceValue, double otherValue, doub return Math.Abs(referenceValue - otherValue) <= maxVariation; } + /// + /// Checks if two values are equal with a given relative tolerance. + /// + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a percentage of . A relative tolerance of + /// 0.01 means the + /// absolute difference of and must be within +/- + /// 1%. + /// + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// + /// EqualsRelative(a, b, 0.01); + /// + /// + /// + /// + /// The reference value which the tolerance will be calculated against. + /// The value to compare to. + /// The relative tolerance. Must be greater than or equal to 0. + /// True if the two values are equal within the given relative tolerance, otherwise false. + 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; + } + /// /// Checks if two values are equal with a given absolute tolerance. /// @@ -121,5 +206,32 @@ public static bool EqualsAbsolute(double value1, double value2, double tolerance return Math.Abs(value1 - value2) <= tolerance; } + + /// + /// Checks if two values are equal with a given absolute tolerance. + /// + /// Absolute tolerance is defined as the maximum allowable absolute difference between + /// and + /// as a fixed number. + /// + /// In this example, the two values will be equal if abs( - + /// ) <= 0.01 + /// + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// + /// + /// + /// + /// The first value. + /// The second value. + /// The absolute tolerance. Must be greater than or equal to 0. + /// True if the two values are equal within the given absolute tolerance, otherwise false. + 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/CustomCode/GlobalConfiguration.cs b/UnitsNet/CustomCode/GlobalConfiguration.cs deleted file mode 100644 index 746e98dc65..0000000000 --- a/UnitsNet/CustomCode/GlobalConfiguration.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed under MIT 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.Threading; - -// ReSharper disable once CheckNamespace -namespace UnitsNet -{ - /// - /// Global configuration for culture, used as default culture in methods like and - /// . - /// - [Obsolete("The only property DefaultCulture is now deprecated. Manipulate Thread.CurrentThread.CurrentUICulture instead.")] - public static class GlobalConfiguration - { - /// - /// Wrapper for . - /// - [Obsolete("Manipulate Thread.CurrentThread.CurrentUICulture instead, this property will be removed.")] - public static IFormatProvider DefaultCulture - { - get => Thread.CurrentThread.CurrentUICulture; - set => Thread.CurrentThread.CurrentUICulture = (CultureInfo) value; - } - } -} diff --git a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs index 44688f7ed9..6fb8944cfe 100644 --- a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs @@ -10,9 +10,9 @@ namespace UnitsNet public partial struct AmountOfSubstance { /// - /// The Avogadro constant is the number of constituent particles, usually molecules, - /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor that relates - /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value + /// The Avogadro constant is the number of constituent particles, usually molecules, + /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor that relates + /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value /// 6.02214076e23 mol−1 in the International System of Units (SI). /// /// @@ -34,13 +34,12 @@ public double NumberOfParticles() return AvogadroConstant * moles.Value; } - /// Get from and a given . public static AmountOfSubstance FromMass(Mass mass, MolarMass molarMass) { return mass / molarMass; } - + /// Get from for a given . public static Mass operator *(AmountOfSubstance amountOfSubstance, MolarMass molarMass) { diff --git a/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs b/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs index 6afa77213e..2d254b9c17 100644 --- a/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs @@ -1,8 +1,6 @@ // Licensed under MIT 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 { public partial struct AreaMomentOfInertia diff --git a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs index 5bd29a877a..a394b46629 100644 --- a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs +++ b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs @@ -1,6 +1,8 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using UnitsNet.Units; + namespace UnitsNet { public partial struct BrakeSpecificFuelConsumption @@ -8,7 +10,7 @@ public partial struct BrakeSpecificFuelConsumption /// Get from times . public static MassFlow operator *(BrakeSpecificFuelConsumption bsfc, Power power) { - return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule*power.Watts); + return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * (double)power.Watts); } /// Get from divided by . diff --git a/UnitsNet/CustomCode/Quantities/Density.extra.cs b/UnitsNet/CustomCode/Quantities/Density.extra.cs index d20459ed7b..fd036dc519 100644 --- a/UnitsNet/CustomCode/Quantities/Density.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Density.extra.cs @@ -1,38 +1,12 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using System; using UnitsNet.Units; namespace UnitsNet { public partial struct Density { - /// - /// Gets from this . - /// - /// - /// - [Obsolete("This method is deprecated in favor of MassConcentration.ToMolarity(MolarMass).")] - public Molarity ToMolarity(Mass molecularWeight) - { - return Molarity.FromMolesPerCubicMeter(KilogramsPerCubicMeter / molecularWeight.Kilograms); - } - - #region Static Methods - - /// - /// Get from . - /// - /// - [Obsolete("This method is deprecated in favor of MassConcentration.FromMolarity(Molarity, MolarMass).")] - public static Density FromMolarity(Molarity molarity, Mass molecularWeight) - { - return new Density(molarity.MolesPerCubicMeter * molecularWeight.Kilograms, DensityUnit.KilogramPerCubicMeter); - } - - #endregion - /// Get from times . public static Mass operator *(Density density, Volume volume) { @@ -63,14 +37,6 @@ public static Density FromMolarity(Molarity molarity, Mass molecularWeight) return new SpecificWeight(density.KilogramsPerCubicMeter * acceleration.MetersPerSecondSquared, SpecificWeightUnit.NewtonPerCubicMeter); } - /// Get from divided by . - /// - [Obsolete("This operator is deprecated in favor of MassConcentration.op_Division(MassConcentration, MolarMass).")] - public static Molarity operator /(Density density, Mass molecularWeight) - { - return new Molarity(density.KilogramsPerCubicMeter / molecularWeight.Kilograms, MolarityUnit.MolesPerCubicMeter); - } - /// Get from times . public static LinearDensity operator *(Density density, Area area) { diff --git a/UnitsNet/CustomCode/Quantities/Energy.extra.cs b/UnitsNet/CustomCode/Quantities/Energy.extra.cs index c132dd6e85..6bc13eb828 100644 --- a/UnitsNet/CustomCode/Quantities/Energy.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Energy.extra.cs @@ -22,7 +22,7 @@ public partial struct Energy /// Get from divided by . public static Duration operator /(Energy energy, Power power) { - return Duration.FromSeconds(energy.Joules / power.Watts); + return Duration.FromSeconds(energy.Joules / (double)power.Watts); } /// Get from times . diff --git a/UnitsNet/CustomCode/Quantities/Length.extra.cs b/UnitsNet/CustomCode/Quantities/Length.extra.cs index 0ed6562c1d..d2401277e1 100644 --- a/UnitsNet/CustomCode/Quantities/Length.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Length.extra.cs @@ -5,7 +5,6 @@ using System.Globalization; using System.Text.RegularExpressions; using System.Threading; -using JetBrains.Annotations; using UnitsNet.Units; namespace UnitsNet @@ -59,7 +58,7 @@ public static Length FromFeetInches(double feet, double inches) /// /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to thread's culture. /// Parsed length. - public static Length ParseFeetInches([NotNull] string str, IFormatProvider? formatProvider = null) + public static Length ParseFeetInches(string str, IFormatProvider? formatProvider = null) { if (str == null) throw new ArgumentNullException(nameof(str)); if (!TryParseFeetInches(str, out Length result, formatProvider)) @@ -223,11 +222,11 @@ public override string ToString() /// Length.FromFeetInches(3,2).FeetInches.ToString() outputs: "3 ft 2 in" /// /// Optional culture to format number and localize unit abbreviations. - /// If null, defaults to . + /// If null, defaults to . /// public string ToString(IFormatProvider? cultureInfo) { - cultureInfo = cultureInfo ?? CultureInfo.CurrentUICulture; + cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; var footUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LengthUnit.Foot, cultureInfo); var inchUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(LengthUnit.Inch, cultureInfo); diff --git a/UnitsNet/CustomCode/Quantities/Mass.extra.cs b/UnitsNet/CustomCode/Quantities/Mass.extra.cs index 0436e2aa63..2db89dfd84 100644 --- a/UnitsNet/CustomCode/Quantities/Mass.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Mass.extra.cs @@ -4,7 +4,6 @@ using System; using System.Threading; using System.Globalization; -using JetBrains.Annotations; using UnitsNet.Units; namespace UnitsNet @@ -139,11 +138,11 @@ public override string ToString() /// Mass.FromStonePounds(3,2).StonePounds.ToString() outputs: "3 st 2 lb" /// /// Optional culture to format number and localize unit abbreviations. - /// If null, defaults to . + /// If null, defaults to . /// public string ToString(IFormatProvider? cultureInfo) { - cultureInfo = cultureInfo ?? CultureInfo.CurrentUICulture; + cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; var stoneUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(MassUnit.Stone, cultureInfo); var poundUnit = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(MassUnit.Pound, cultureInfo); diff --git a/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs b/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs index edce6c4ee2..3e02c6e53d 100644 --- a/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs @@ -1,8 +1,6 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.Units; - namespace UnitsNet { public partial struct MassConcentration @@ -26,7 +24,6 @@ public VolumeConcentration ToVolumeConcentration(Density componentDensity) return this / componentDensity; } - #region Static Methods /// @@ -48,7 +45,7 @@ public static MassConcentration FromVolumeConcentration(VolumeConcentration volu #endregion #region Operators - + /// Get from times . public static Mass operator *(MassConcentration density, Volume volume) { @@ -60,7 +57,7 @@ public static MassConcentration FromVolumeConcentration(VolumeConcentration volu { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - + /// Get from divided by the component's . public static Molarity operator /(MassConcentration massConcentration, MolarMass componentMass) { diff --git a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs index e60c5c75d8..609db1ddef 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs @@ -2,6 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using UnitsNet.Units; namespace UnitsNet { @@ -40,7 +41,7 @@ public partial struct MassFlow /// Get from divided by . public static BrakeSpecificFuelConsumption operator /(MassFlow massFlow, Power power) { - return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(massFlow.KilogramsPerSecond / power.Watts); + return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(massFlow.KilogramsPerSecond / (double)power.Watts); } /// Get from times . diff --git a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs index 53af6eeb15..8d6079c9e4 100644 --- a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs @@ -1,40 +1,16 @@ -using System; -using UnitsNet.Units; +using UnitsNet.Units; namespace UnitsNet { public partial struct Molarity { - /// - /// Construct from divided by . - /// - /// - [Obsolete("This constructor will be removed in favor of operator overload MassConcentration.op_Division(MassConcentration,MolarMass).")] - public Molarity(Density density, Mass molecularWeight) - : this() - { - _value = density.KilogramsPerCubicMeter / molecularWeight.Kilograms; - _unit = MolarityUnit.MolesPerCubicMeter; - } - - /// - /// Get a from this . - /// - /// - /// - [Obsolete("This method will be removed in favor of ToMassConcentration(MolarMass)")] - public Density ToDensity(Mass molecularWeight) - { - return Density.FromKilogramsPerCubicMeter(MolesPerCubicMeter * molecularWeight.Kilograms); - } - /// /// Get a from this . /// /// - public MassConcentration ToMassConcentration(MolarMass molecularWeight) + public MassConcentration ToMassConcentration(MolarMass molecularWeight) { - return this * molecularWeight; + return this * molecularWeight; } /// @@ -49,17 +25,6 @@ public VolumeConcentration ToVolumeConcentration(Density componentDensity, Molar #region Static Methods - /// - /// Get from . - /// - /// - /// - [Obsolete("Use MassConcentration / MolarMass operator overload instead.")] - public static Molarity FromDensity(Density density, Mass molecularWeight) - { - return density / molecularWeight; - } - /// /// Get from and known component and . /// diff --git a/UnitsNet/CustomCode/Quantities/Power.extra.cs b/UnitsNet/CustomCode/Quantities/Power.extra.cs index 187c2740fc..61739b4054 100644 --- a/UnitsNet/CustomCode/Quantities/Power.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Power.extra.cs @@ -2,6 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using UnitsNet.Units; namespace UnitsNet { @@ -24,87 +25,87 @@ public PowerRatio ToPowerRatio() /// Get from times . public static Energy operator *(Power power, TimeSpan time) { - return Energy.FromJoules(power.Watts * time.TotalSeconds); + return Energy.FromJoules((double)power.Watts * time.TotalSeconds); } /// Get from times . public static Energy operator *(TimeSpan time, Power power) { - return Energy.FromJoules(power.Watts * time.TotalSeconds); + return Energy.FromJoules((double)power.Watts * time.TotalSeconds); } /// Get from times . public static Energy operator *(Power power, Duration duration) { - return Energy.FromJoules(power.Watts * duration.Seconds); + return Energy.FromJoules((double)power.Watts * duration.Seconds); } /// Get from times . public static Energy operator *(Duration duration, Power power) { - return Energy.FromJoules(power.Watts * duration.Seconds); + return Energy.FromJoules((double)power.Watts * duration.Seconds); } /// Get from divided by . public static Force operator /(Power power, Speed speed) { - return Force.FromNewtons(power.Watts / speed.MetersPerSecond); + return Force.FromNewtons((double)power.Watts / speed.MetersPerSecond); } /// Get from divided by . public static Torque operator /(Power power, RotationalSpeed rotationalSpeed) { - return Torque.FromNewtonMeters(power.Watts / rotationalSpeed.RadiansPerSecond); + return Torque.FromNewtonMeters((double)power.Watts / rotationalSpeed.RadiansPerSecond); } /// Get from divided by . public static RotationalSpeed operator /(Power power, Torque torque) { - return RotationalSpeed.FromRadiansPerSecond(power.Watts / torque.NewtonMeters); + return RotationalSpeed.FromRadiansPerSecond((double)power.Watts / torque.NewtonMeters); } /// Get from times . public static MassFlow operator *(Power power, BrakeSpecificFuelConsumption bsfc) { - return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * power.Watts); + return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * (double)power.Watts); } /// Get from divided by . public static SpecificEnergy operator /(Power power, MassFlow massFlow) { - return SpecificEnergy.FromJoulesPerKilogram(power.Watts / massFlow.KilogramsPerSecond); + return SpecificEnergy.FromJoulesPerKilogram((double)power.Watts / massFlow.KilogramsPerSecond); } /// Get from divided by . public static MassFlow operator /(Power power, SpecificEnergy specificEnergy) { - return MassFlow.FromKilogramsPerSecond(power.Watts / specificEnergy.JoulesPerKilogram); + return MassFlow.FromKilogramsPerSecond((double)power.Watts / specificEnergy.JoulesPerKilogram); } /// Get from divided by . public static HeatFlux operator /(Power power, Area area) { - return HeatFlux.FromWattsPerSquareMeter(power.Watts / area.SquareMeters); + return HeatFlux.FromWattsPerSquareMeter((double)power.Watts / area.SquareMeters); } /// Get from divided by . public static Area operator /(Power power, HeatFlux heatFlux) { - return Area.FromSquareMeters( power.Watts / heatFlux.WattsPerSquareMeter ); + return Area.FromSquareMeters((double)power.Watts / heatFlux.WattsPerSquareMeter ); } /// Calculate from divided by . /// Electric power is defined as P = U * I, so I = P / U. public static ElectricCurrent operator /(Power power, ElectricPotential potential) { - return ElectricCurrent.FromAmperes(power.Watts / potential.Volts); + return ElectricCurrent.FromAmperes((double)power.Watts / potential.Volts); } /// Calculate from divided by . /// Electric power is defined as P = U * I, so I = P / U. public static ElectricPotential operator /(Power power, ElectricCurrent current) { - return ElectricPotential.FromVolts(power.Watts / current.Amperes); + return ElectricPotential.FromVolts((double)power.Watts / current.Amperes); } } } diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index f563f720ae..e4c4f07fe6 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -21,7 +21,7 @@ public PowerRatio(Power power) nameof(power), "The base-10 logarithm of a number ≤ 0 is undefined. Power must be greater than 0 W."); // P(dBW) = 10*log10(value(W)/reference(W)) - _value = 10 * Math.Log10(power.Watts / 1); + _value = 10 * Math.Log10((double)power.Watts); _unit = PowerRatioUnit.DecibelWatt; } diff --git a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs index 85f4f8bae1..0a6bd6e6d9 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs @@ -10,7 +10,7 @@ public partial struct SpecificWeight /// Get from times . public static Pressure operator *(SpecificWeight specificWeight, Length length) { - return new Pressure(specificWeight.NewtonsPerCubicMeter * length.Meters, UnitsNet.Units.PressureUnit.Pascal); + return new Pressure(specificWeight.NewtonsPerCubicMeter * length.Meters, PressureUnit.Pascal); } /// Get from times . @@ -28,13 +28,13 @@ public partial struct SpecificWeight /// Get from divided by . public static Acceleration operator /(SpecificWeight specificWeight, Density density) { - return new Acceleration(specificWeight.NewtonsPerCubicMeter / density.KilogramsPerCubicMeter, UnitsNet.Units.AccelerationUnit.MeterPerSecondSquared); + return new Acceleration(specificWeight.NewtonsPerCubicMeter / density.KilogramsPerCubicMeter, AccelerationUnit.MeterPerSecondSquared); } /// Get from divided by . public static Density operator /(SpecificWeight specific, Acceleration acceleration) { - return new Density(specific.NewtonsPerCubicMeter / acceleration.MetersPerSecondSquared, UnitsNet.Units.DensityUnit.KilogramPerCubicMeter); + return new Density(specific.NewtonsPerCubicMeter / acceleration.MetersPerSecondSquared, DensityUnit.KilogramPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs index cfce09a948..4556009fc6 100644 --- a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs @@ -64,7 +64,6 @@ public Temperature Multiply(double factor, TemperatureUnit unit) return From(resultInUnit, unit); } - /// /// Divide temperature by a in a given . /// diff --git a/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs b/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs index e90942cfd1..fed1b0ca30 100644 --- a/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs @@ -46,7 +46,6 @@ public static VolumeConcentration FromMolarity(Molarity molarity, Density compon return molarity * componentMolarMass / componentDensity; } - #endregion #region Operators @@ -56,13 +55,13 @@ public static VolumeConcentration FromMolarity(Molarity molarity, Density compon { return MassConcentration.FromKilogramsPerCubicMeter(volumeConcentration.DecimalFractions * componentDensity.KilogramsPerCubicMeter); } - + /// Get from times the component . public static MassConcentration operator *(Density componentDensity, VolumeConcentration volumeConcentration) { return MassConcentration.FromKilogramsPerCubicMeter(volumeConcentration.DecimalFractions * componentDensity.KilogramsPerCubicMeter); } - + #endregion } diff --git a/UnitsNet/CustomCode/Quantity.cs b/UnitsNet/CustomCode/Quantity.cs index 838d4d9cb1..0f0511b5bb 100644 --- a/UnitsNet/CustomCode/Quantity.cs +++ b/UnitsNet/CustomCode/Quantity.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using UnitsNet.InternalHelpers; namespace UnitsNet { @@ -14,7 +13,6 @@ public partial class Quantity static Quantity() { ICollection quantityInfos = ByName.Values; - Types = Enum.GetValues(typeof(QuantityType)).Cast().Except(new[] { QuantityType.Undefined }).ToArray(); Names = quantityInfos.Select(qt => qt.Name).ToArray(); InfosLazy = new Lazy(() => quantityInfos @@ -32,12 +30,6 @@ static Quantity() }); } - /// - /// All enum values of , such as and . - /// - [Obsolete("QuantityType will be removed in the future. Use Infos property instead.")] - public static QuantityType[] Types { get; } - /// /// All enum value names of , such as "Length" and "Mass". /// @@ -95,14 +87,14 @@ public static bool TryFrom(double value, Enum unit, out IQuantity? quantity) /// /// Dynamically parse a quantity string representation. /// - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Type of quantity, such as . /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. /// The parsed quantity. /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. public static IQuantity Parse(IFormatProvider? formatProvider, Type quantityType, string quantityString) { - if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) + if (!typeof(IQuantity).IsAssignableFrom(quantityType)) throw new ArgumentException($"Type {quantityType} must be of type UnitsNet.IQuantity."); if (TryParse(formatProvider, quantityType, quantityString, out IQuantity? quantity)) @@ -115,17 +107,6 @@ public static IQuantity Parse(IFormatProvider? formatProvider, Type quantityType public static bool TryParse(Type quantityType, string quantityString, out IQuantity? quantity) => TryParse(null, quantityType, quantityString, out quantity); - /// - /// Get information about the given quantity type. - /// - /// The quantity type enum value. - /// Information about the quantity and its units. - [Obsolete("QuantityType will be removed in the future.")] - public static QuantityInfo GetInfo(QuantityType quantityType) - { - return Infos.First(qi => qi.QuantityType == quantityType); - } - /// /// Get a list of quantities that has the given base dimensions. /// diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index 8e5db0b810..b5f4ecb012 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -7,7 +7,6 @@ using System.Globalization; using System.Linq; using System.Text.RegularExpressions; -using JetBrains.Annotations; // ReSharper disable once CheckNamespace namespace UnitsNet @@ -29,7 +28,7 @@ internal class QuantityParser public static QuantityParser Default { get; } - public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache) + public QuantityParser(UnitAbbreviationsCache? unitAbbreviationsCache) { _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; _unitParser = new UnitParser(_unitAbbreviationsCache); @@ -41,22 +40,15 @@ static QuantityParser() } [SuppressMessage("ReSharper", "UseStringInterpolation")] - internal TQuantity Parse([NotNull] string str, + internal TQuantity Parse(string str, IFormatProvider? formatProvider, - [NotNull] QuantityFromDelegate fromDelegate) + QuantityFromDelegate fromDelegate) where TQuantity : IQuantity where TUnitType : Enum { if (str == null) throw new ArgumentNullException(nameof(str)); str = str.Trim(); - var numFormat = formatProvider != null - ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) - : NumberFormatInfo.CurrentInfo; - - if (numFormat == null) - throw new InvalidOperationException($"No number format was found for the given format provider: {formatProvider}"); - var regex = CreateRegexForQuantity(formatProvider); if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString)) @@ -72,38 +64,29 @@ internal TQuantity Parse([NotNull] string str, [SuppressMessage("ReSharper", "UseStringInterpolation")] internal bool TryParse(string? str, IFormatProvider? formatProvider, - [NotNull] QuantityFromDelegate fromDelegate, + QuantityFromDelegate fromDelegate, out TQuantity result) where TQuantity : struct, IQuantity where TUnitType : struct, Enum { result = default; - if (string.IsNullOrWhiteSpace(str)) return false; + if(string.IsNullOrWhiteSpace(str)) return false; str = str!.Trim(); - var numFormat = formatProvider != null - ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) - : NumberFormatInfo.CurrentInfo; - - if (numFormat == null) - return false; - var regex = CreateRegexForQuantity(formatProvider); - if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString)) - return false; - - return TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); + return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) && + TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); } /// /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are compatible. /// [SuppressMessage("ReSharper", "UseStringInterpolation")] - internal bool TryParse([NotNull] string str, + internal bool TryParse(string str, IFormatProvider? formatProvider, - [NotNull] QuantityFromDelegate fromDelegate, + QuantityFromDelegate fromDelegate, out IQuantity? result) where TQuantity : struct, IQuantity where TUnitType : struct, Enum @@ -187,7 +170,7 @@ private static bool TryExtractValueAndUnit(Regex regex, string str, out string? // 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] - // Therefor a mismatch can be detected by comparing the values of this two groups. + // 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); diff --git a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs index e5e4817487..45078f6cd0 100644 --- a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs +++ b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs @@ -6,8 +6,6 @@ using System.Globalization; using System.Linq; using System.Reflection; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; using UnitsNet.Units; using UnitTypeToLookup = System.Collections.Generic.Dictionary; @@ -32,7 +30,7 @@ public sealed class UnitAbbreviationsCache /// 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. /// - private static readonly CultureInfo FallbackCulture = new CultureInfo("en-US"); + internal static readonly CultureInfo FallbackCulture = new("en-US"); /// /// The static instance used internally for ToString() and Parse() of quantities and units. @@ -71,10 +69,9 @@ private void LoadGeneratedAbbreviations() /// The unit enum value. /// Unit abbreviations to add. /// The type of unit enum. - [PublicAPI] public void MapUnitToAbbreviation(TUnitType unit, params string[] abbreviations) where TUnitType : Enum { - PerformAbbreviationMapping(unit, CultureInfo.CurrentUICulture, false, true, abbreviations); + PerformAbbreviationMapping(unit, CultureInfo.CurrentCulture, false, true, abbreviations); } /// @@ -87,7 +84,7 @@ public void MapUnitToAbbreviation(TUnitType unit, params string[] abb /// The type of unit enum. public void MapUnitToDefaultAbbreviation(TUnitType unit, string abbreviation) where TUnitType : Enum { - PerformAbbreviationMapping(unit, CultureInfo.CurrentUICulture, true, true, abbreviation); + PerformAbbreviationMapping(unit, CultureInfo.CurrentCulture, true, true, abbreviation); } /// @@ -96,11 +93,10 @@ public void MapUnitToDefaultAbbreviation(TUnitType unit, string abbre /// in order to or on them later. /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations to add. /// The type of unit enum. - [PublicAPI] - public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider formatProvider, params string[] abbreviations) where TUnitType : Enum + public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider? formatProvider, params string[] abbreviations) where TUnitType : Enum { PerformAbbreviationMapping(unit, formatProvider, false, true, abbreviations); } @@ -111,11 +107,10 @@ public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider for /// in order to or on them later. /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviation to add as default. /// The type of unit enum. - [PublicAPI] - public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvider formatProvider, string abbreviation) where TUnitType : Enum + public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvider? formatProvider, string abbreviation) where TUnitType : Enum { PerformAbbreviationMapping(unit, formatProvider, true, true, abbreviation); } @@ -127,10 +122,9 @@ public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvi /// /// The unit enum type. /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations to add. - [PublicAPI] - public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] params string[] abbreviations) + 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); @@ -143,21 +137,20 @@ public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider /// /// The unit enum type. /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviation to add as default. - [PublicAPI] - public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] string abbreviation) + 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, [NotNull] params string[] abbreviations) + internal void PerformAbbreviationMapping(Enum unitValue, IFormatProvider? formatProvider, bool setAsDefault, bool allowAbbreviationLookup, params string[] abbreviations) { if (abbreviations == null) throw new ArgumentNullException(nameof(abbreviations)); - formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; + formatProvider ??= CultureInfo.CurrentCulture; if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) quantitiesForProvider = _lookupsForCulture[formatProvider] = new UnitTypeToLookup(); @@ -178,29 +171,26 @@ internal void PerformAbbreviationMapping(Enum unitValue, IFormatProvider formatP /// Example: GetDefaultAbbreviation<LengthUnit>(LengthUnit.Kilometer) => "km" /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// The type of unit enum. /// The default unit abbreviation string. - [PublicAPI] public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider? formatProvider = null) where TUnitType : Enum { var unitType = typeof(TUnitType); if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) { - if (formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unit, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + 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) { - if (formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unit, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + return !Equals(formatProvider, FallbackCulture) + ? GetDefaultAbbreviation(unit, FallbackCulture) + : throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); } return abbreviations.First(); @@ -213,26 +203,23 @@ public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider? /// /// The unit enum type. /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// The default unit abbreviation string. - [PublicAPI] public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider = null) { if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) { - if (formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{Enum.GetName(unitType, unitValue)}."); + 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) { - if (formatProvider != FallbackCulture) - return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{Enum.GetName(unitType, unitValue)}."); + 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(); @@ -243,9 +230,8 @@ public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvid /// /// Enum type for units. /// Enum value for unit. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. - [PublicAPI] public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider? formatProvider = null) where TUnitType : Enum { return GetUnitAbbreviations(typeof(TUnitType), Convert.ToInt32(unit), formatProvider); @@ -256,19 +242,26 @@ public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider? /// /// Enum type for unit. /// Enum value for unit. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. - [PublicAPI] public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider? formatProvider = null) { - formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; + formatProvider ??= CultureInfo.CurrentCulture; if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) - return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; + { + return !Equals(formatProvider, FallbackCulture) + ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) + : new string[] { }; + } var abbreviations = lookup!.GetAbbreviationsForUnit(unitValue); if (abbreviations.Count == 0) - return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; + { + return !Equals(formatProvider, FallbackCulture) + ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) + : new string[] { }; + } return abbreviations.ToArray(); } @@ -277,15 +270,18 @@ public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvid /// Get all abbreviations for all units of a quantity. /// /// Enum type for unit. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. - [PublicAPI] public string[] GetAllUnitAbbreviationsForQuantity(Type unitEnumType, IFormatProvider? formatProvider = null) { - formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; + formatProvider ??= CultureInfo.CurrentCulture; if (!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) - return formatProvider != FallbackCulture ? GetAllUnitAbbreviationsForQuantity(unitEnumType, FallbackCulture) : new string[] { }; + { + return !Equals(formatProvider, FallbackCulture) + ? GetAllUnitAbbreviationsForQuantity(unitEnumType, FallbackCulture) + : new string[] { }; + } return lookup!.GetAllUnitAbbreviationsForQuantity(); } @@ -294,13 +290,19 @@ internal bool TryGetUnitValueAbbreviationLookup(Type unitType, IFormatProvider? { unitToAbbreviations = null; - formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; + formatProvider ??= CultureInfo.CurrentCulture; if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) - return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; + { + return !Equals(formatProvider, FallbackCulture) && + TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations); + } if (!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) - return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; + { + return !Equals(formatProvider, FallbackCulture) && + TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations); + } return true; } diff --git a/UnitsNet/CustomCode/UnitParser.cs b/UnitsNet/CustomCode/UnitParser.cs index a80b2b931f..4a673bd593 100644 --- a/UnitsNet/CustomCode/UnitParser.cs +++ b/UnitsNet/CustomCode/UnitParser.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; using System.Linq; -using JetBrains.Annotations; using UnitsNet.Units; // ReSharper disable once CheckNamespace @@ -29,7 +28,7 @@ public sealed class UnitParser /// Create a parser using the given unit abbreviations cache. /// /// - public UnitParser(UnitAbbreviationsCache unitAbbreviationsCache) + public UnitParser(UnitAbbreviationsCache? unitAbbreviationsCache) { _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; } @@ -44,10 +43,9 @@ static UnitParser() /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer /// /// - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// /// - [PublicAPI] public TUnitType Parse(string unitAbbreviation, IFormatProvider? formatProvider = null) where TUnitType : Enum { return (TUnitType)Parse(unitAbbreviation, typeof(TUnitType), formatProvider); @@ -62,12 +60,11 @@ public TUnitType Parse(string unitAbbreviation, IFormatProvider? form /// respectively. /// /// Unit enum type, such as and . - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Unit enum value, such as . /// No units match the abbreviation. /// More than one unit matches the abbreviation. - [PublicAPI] - public Enum Parse([NotNull] string unitAbbreviation, Type unitType, IFormatProvider? formatProvider = null) + public Enum Parse(string? unitAbbreviation, Type unitType, IFormatProvider? formatProvider = null) { if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); unitAbbreviation = unitAbbreviation.Trim(); @@ -92,6 +89,12 @@ public Enum Parse([NotNull] string unitAbbreviation, Type unitType, IFormatProvi 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()); @@ -138,7 +141,6 @@ internal static string NormalizeUnitString(string unitAbbreviation) /// The unit enum value as out result. /// Type of unit enum. /// True if successful. - [PublicAPI] public bool TryParse(string unitAbbreviation, out TUnitType unit) where TUnitType : struct, Enum { return TryParse(unitAbbreviation, null, out unit); @@ -148,11 +150,10 @@ public bool TryParse(string unitAbbreviation, out TUnitType unit) whe /// Try to parse a unit abbreviation. /// /// The string value. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// The unit enum value as out result. /// Type of unit enum. /// True if successful. - [PublicAPI] public bool TryParse(string? unitAbbreviation, IFormatProvider? formatProvider, out TUnitType unit) where TUnitType : struct, Enum { unit = default; @@ -171,7 +172,6 @@ public bool TryParse(string? unitAbbreviation, IFormatProvider? forma /// Type of unit enum. /// The unit enum value as out result. /// True if successful. - [PublicAPI] public bool TryParse(string unitAbbreviation, Type unitType, out Enum? unit) { return TryParse(unitAbbreviation, unitType, null, out unit); @@ -182,10 +182,9 @@ public bool TryParse(string unitAbbreviation, Type unitType, out Enum? unit) /// /// The string value. /// Type of unit enum. - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// The unit enum value as out result. /// True if successful. - [PublicAPI] public bool TryParse(string? unitAbbreviation, Type unitType, IFormatProvider? formatProvider, out Enum? unit) { if (unitAbbreviation == null) diff --git a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs index 3e41efb2f8..0c2ed3b643 100644 --- a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs +++ b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs @@ -12,27 +12,24 @@ namespace UnitsNet { internal class UnitValueAbbreviationLookup { - private readonly UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); - private readonly AbbreviationToUnitMap abbreviationToUnitMap = new AbbreviationToUnitMap(); - private readonly AbbreviationToUnitMap lowerCaseAbbreviationToUnitMap = new AbbreviationToUnitMap(); + private readonly UnitToAbbreviationMap _unitToAbbreviationMap = new(); + private readonly AbbreviationToUnitMap _abbreviationToUnitMap = new(); + private readonly AbbreviationToUnitMap _lowerCaseAbbreviationToUnitMap = new(); internal string[] GetAllUnitAbbreviationsForQuantity() { - return unitToAbbreviationMap.Values.SelectMany((abbreviations) => - { - return abbreviations; - } ).Distinct().ToArray(); + return _unitToAbbreviationMap.Values.SelectMany(abbreviations => abbreviations).Distinct().ToArray(); } - internal List GetAbbreviationsForUnit(UnitType unit) where UnitType : Enum + internal List GetAbbreviationsForUnit(TUnitType unit) where TUnitType : Enum { return GetAbbreviationsForUnit(Convert.ToInt32(unit)); } internal List GetAbbreviationsForUnit(int unit) { - if (!unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) - unitToAbbreviationMap[unit] = abbreviations = new List(); + if (!_unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) + _unitToAbbreviationMap[unit] = abbreviations = new List(); return abbreviations.Distinct().ToList(); } @@ -41,7 +38,7 @@ internal List GetUnitsForAbbreviation(string abbreviation, bool ignoreCase) { var lowerCaseAbbreviation = abbreviation.ToLower(); var key = ignoreCase ? lowerCaseAbbreviation : abbreviation; - var map = ignoreCase ? lowerCaseAbbreviationToUnitMap : abbreviationToUnitMap; + var map = ignoreCase ? _lowerCaseAbbreviationToUnitMap : _abbreviationToUnitMap; if (!map.TryGetValue(key, out List units)) map[key] = units = new List(); @@ -53,16 +50,16 @@ internal void Add(int unit, string abbreviation, bool setAsDefault = false, bool { var lowerCaseAbbreviation = abbreviation.ToLower(); - if (!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) - abbreviationsForUnit = unitToAbbreviationMap[unit] = new List(); + if (!_unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) + abbreviationsForUnit = _unitToAbbreviationMap[unit] = new List(); if (allowAbbreviationLookup) { - if (!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) - abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List(); + if (!_abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) + _abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List(); - if (!lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) - lowerCaseAbbreviationToUnitMap[lowerCaseAbbreviation] = unitsForLowerCaseAbbreviation = new List(); + if (!_lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) + _lowerCaseAbbreviationToUnitMap[lowerCaseAbbreviation] = unitsForLowerCaseAbbreviation = new List(); unitsForLowerCaseAbbreviation.Remove(unit); unitsForLowerCaseAbbreviation.Add(unit); diff --git a/UnitsNet/CustomCode/Units/PressureReference.cs b/UnitsNet/CustomCode/Units/PressureReference.cs index e2d224d60d..7918f67d87 100644 --- a/UnitsNet/CustomCode/Units/PressureReference.cs +++ b/UnitsNet/CustomCode/Units/PressureReference.cs @@ -25,7 +25,6 @@ namespace UnitsNet.CustomCode.Units public enum PressureReference { - Undefined = 0, Absolute, Gauge, Vacuum, diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index c11d4a34c9..5291b7d77b 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -2,12 +2,11 @@ // 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; using UnitsNet.CustomCode.Units; using UnitsNet.Units; -namespace UnitsNet.CustomCode.Wrappers +namespace UnitsNet.Wrappers { /// /// Pressure tied to a real-world reference, allowing conversion between references. @@ -37,7 +36,7 @@ public struct ReferencePressure /// , and /// public static PressureReference[] References { get; } = - Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToArray(); + Enum.GetValues(typeof(PressureReference)).Cast().ToArray(); /// /// Initializes a new instance of the struct requiring measured @@ -165,7 +164,7 @@ private double AsBaseReference() { if (Pressure.Value < 0) { - throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + throw new ArgumentOutOfRangeException(nameof(Pressure), "Absolute pressure cannot be less than zero."); } return Pressure.Value; @@ -174,7 +173,7 @@ private double AsBaseReference() { if (Pressure.Value * -1 > AtmosphericPressure.ToUnit(Pressure.Unit).Value) { - throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + throw new ArgumentOutOfRangeException(nameof(Pressure), "Absolute pressure cannot be less than zero."); } return AtmosphericPressure.ToUnit(Pressure.Unit).Value + Pressure.Value; @@ -183,7 +182,7 @@ private double AsBaseReference() { if (Pressure.Value > AtmosphericPressure.ToUnit(Pressure.Unit).Value) { - throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + throw new ArgumentOutOfRangeException(nameof(Pressure), "Absolute pressure cannot be less than zero."); } return AtmosphericPressure.ToUnit(Pressure.Unit).Value - Pressure.Value; diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index 13346aac2d..576f94fc12 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration. /// [DataContract] - public readonly partial struct Acceleration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Acceleration : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Acceleration() { BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); BaseUnit = AccelerationUnit.MeterPerSecondSquared; - MaxValue = new Acceleration(double.MaxValue, BaseUnit); - MinValue = new Acceleration(double.MinValue, BaseUnit); - QuantityType = QuantityType.Acceleration; - Units = Enum.GetValues(typeof(AccelerationUnit)).Cast().Except(new AccelerationUnit[]{ AccelerationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AccelerationUnit)).Cast().ToArray(); Zero = new Acceleration(0, BaseUnit); Info = new QuantityInfo("Acceleration", new UnitInfo[] @@ -77,7 +73,7 @@ static Acceleration() new UnitInfo(AccelerationUnit.NanometerPerSecondSquared, "NanometersPerSecondSquared", BaseUnits.Undefined), new UnitInfo(AccelerationUnit.StandardGravity, "StandardGravity", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Acceleration); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -91,9 +87,6 @@ static Acceleration() /// If value is NaN or Infinity. public Acceleration(double value, AccelerationUnit unit) { - if (unit == AccelerationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -137,24 +130,6 @@ public Acceleration(double value, UnitSystem unitSystem) /// public static AccelerationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Acceleration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Acceleration MaxValue { get; } - - /// - /// Represents the smallest possible value of Acceleration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Acceleration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Acceleration quantity. /// @@ -174,6 +149,9 @@ public Acceleration(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -185,12 +163,6 @@ public Acceleration(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Acceleration; - /// /// The of this quantity. /// @@ -361,7 +333,7 @@ public static string GetAbbreviation(AccelerationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AccelerationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -575,7 +547,7 @@ public static Acceleration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Acceleration Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -606,7 +578,7 @@ public static bool TryParse(string? str, out Acceleration result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Acceleration result) { return QuantityParser.Default.TryParse( @@ -634,7 +606,7 @@ public static AccelerationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -660,7 +632,7 @@ public static bool TryParseUnit(string str, out AccelerationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AccelerationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -740,20 +712,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Accel return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Acceleration left, Acceleration right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Acceleration left, Acceleration right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -769,23 +727,6 @@ public int CompareTo(Acceleration other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Acceleration objAcceleration)) - return false; - - return Equals(objAcceleration); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Acceleration other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Acceleration within the given absolute or relative tolerance. @@ -831,7 +772,7 @@ public bool Equals(Acceleration other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -857,10 +798,9 @@ public override int GetHashCode() public double As(AccelerationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -881,10 +821,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AccelerationUnit unitAsAccelerationUnit)) + if (!(unit is AccelerationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); - return As(unitAsAccelerationUnit); + return (double)As(typedUnit); } /// @@ -983,10 +923,10 @@ private bool TryToUnit(AccelerationUnit unit, out Acceleration? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AccelerationUnit unitAsAccelerationUnit)) + 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(unitAsAccelerationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1030,63 +970,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1168,8 +1074,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AccelerationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Acceleration.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Acceleration.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index b8af658075..76e9593fda 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals. /// [DataContract] - public readonly partial struct AmountOfSubstance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct AmountOfSubstance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static AmountOfSubstance() { BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); BaseUnit = AmountOfSubstanceUnit.Mole; - MaxValue = new AmountOfSubstance(double.MaxValue, BaseUnit); - MinValue = new AmountOfSubstance(double.MinValue, BaseUnit); - QuantityType = QuantityType.AmountOfSubstance; - Units = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().Except(new AmountOfSubstanceUnit[]{ AmountOfSubstanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().ToArray(); Zero = new AmountOfSubstance(0, BaseUnit); Info = new QuantityInfo("AmountOfSubstance", new UnitInfo[] @@ -78,7 +74,7 @@ static AmountOfSubstance() new UnitInfo(AmountOfSubstanceUnit.NanopoundMole, "NanopoundMoles", BaseUnits.Undefined), new UnitInfo(AmountOfSubstanceUnit.PoundMole, "PoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.PoundMole)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.AmountOfSubstance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -92,9 +88,6 @@ static AmountOfSubstance() /// If value is NaN or Infinity. public AmountOfSubstance(double value, AmountOfSubstanceUnit unit) { - if (unit == AmountOfSubstanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -138,24 +131,6 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) /// public static AmountOfSubstanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of AmountOfSubstance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AmountOfSubstance MaxValue { get; } - - /// - /// Represents the smallest possible value of AmountOfSubstance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AmountOfSubstance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the AmountOfSubstance quantity. /// @@ -175,6 +150,9 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -186,12 +164,6 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.AmountOfSubstance; - /// /// The of this quantity. /// @@ -356,7 +328,7 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AmountOfSubstanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -580,7 +552,7 @@ public static AmountOfSubstance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static AmountOfSubstance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -611,7 +583,7 @@ public static bool TryParse(string? str, out AmountOfSubstance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out AmountOfSubstance result) { return QuantityParser.Default.TryParse( @@ -639,7 +611,7 @@ public static AmountOfSubstanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -665,7 +637,7 @@ public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AmountOfSubstanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -745,20 +717,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Amoun return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -774,23 +732,6 @@ public int CompareTo(AmountOfSubstance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is AmountOfSubstance objAmountOfSubstance)) - return false; - - return Equals(objAmountOfSubstance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(AmountOfSubstance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another AmountOfSubstance within the given absolute or relative tolerance. @@ -836,7 +777,7 @@ public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType com if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -862,10 +803,9 @@ public override int GetHashCode() public double As(AmountOfSubstanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -886,10 +826,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AmountOfSubstanceUnit unitAsAmountOfSubstanceUnit)) + if (!(unit is AmountOfSubstanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); - return As(unitAsAmountOfSubstanceUnit); + return (double)As(typedUnit); } /// @@ -990,10 +930,10 @@ private bool TryToUnit(AmountOfSubstanceUnit unit, out AmountOfSubstance? conver /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AmountOfSubstanceUnit unitAsAmountOfSubstanceUnit)) + 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(unitAsAmountOfSubstanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1037,63 +977,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1175,8 +1081,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AmountOfSubstanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return AmountOfSubstance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return AmountOfSubstance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 349912732f..74da1a5124 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. /// [DataContract] - public readonly partial struct AmplitudeRatio : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct AmplitudeRatio : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static AmplitudeRatio() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = AmplitudeRatioUnit.DecibelVolt; - MaxValue = new AmplitudeRatio(double.MaxValue, BaseUnit); - MinValue = new AmplitudeRatio(double.MinValue, BaseUnit); - QuantityType = QuantityType.AmplitudeRatio; - Units = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().Except(new AmplitudeRatioUnit[]{ AmplitudeRatioUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().ToArray(); Zero = new AmplitudeRatio(0, BaseUnit); Info = new QuantityInfo("AmplitudeRatio", new UnitInfo[] @@ -67,7 +63,7 @@ static AmplitudeRatio() new UnitInfo(AmplitudeRatioUnit.DecibelUnloaded, "DecibelsUnloaded", BaseUnits.Undefined), new UnitInfo(AmplitudeRatioUnit.DecibelVolt, "DecibelVolts", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.AmplitudeRatio); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static AmplitudeRatio() /// If value is NaN or Infinity. public AmplitudeRatio(double value, AmplitudeRatioUnit unit) { - if (unit == AmplitudeRatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) /// public static AmplitudeRatioUnit BaseUnit { get; } - /// - /// Represents the largest possible value of AmplitudeRatio - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AmplitudeRatio MaxValue { get; } - - /// - /// Represents the smallest possible value of AmplitudeRatio - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AmplitudeRatio MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the AmplitudeRatio quantity. /// @@ -164,6 +139,9 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.AmplitudeRatio; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AmplitudeRatioUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static AmplitudeRatio Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static AmplitudeRatio Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out AmplitudeRatio result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out AmplitudeRatio result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static AmplitudeRatioUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AmplitudeRatioUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -544,20 +516,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ampli return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -573,23 +531,6 @@ public int CompareTo(AmplitudeRatio other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is AmplitudeRatio objAmplitudeRatio)) - return false; - - return Equals(objAmplitudeRatio); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(AmplitudeRatio other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another AmplitudeRatio within the given absolute or relative tolerance. @@ -635,7 +576,7 @@ public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -661,10 +602,9 @@ public override int GetHashCode() public double As(AmplitudeRatioUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -685,10 +625,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AmplitudeRatioUnit unitAsAmplitudeRatioUnit)) + if (!(unit is AmplitudeRatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); - return As(unitAsAmplitudeRatioUnit); + return (double)As(typedUnit); } /// @@ -767,10 +707,10 @@ private bool TryToUnit(AmplitudeRatioUnit unit, out AmplitudeRatio? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AmplitudeRatioUnit unitAsAmplitudeRatioUnit)) + 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(unitAsAmplitudeRatioUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -814,63 +754,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -952,8 +858,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AmplitudeRatioUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return AmplitudeRatio.QuantityType; else if (conversionType == typeof(QuantityInfo)) return AmplitudeRatio.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index 8c34c6823d..9079e5dd85 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. /// [DataContract] - public readonly partial struct Angle : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Angle : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Angle() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = AngleUnit.Degree; - MaxValue = new Angle(double.MaxValue, BaseUnit); - MinValue = new Angle(double.MinValue, BaseUnit); - QuantityType = QuantityType.Angle; - Units = Enum.GetValues(typeof(AngleUnit)).Cast().Except(new AngleUnit[]{ AngleUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AngleUnit)).Cast().ToArray(); Zero = new Angle(0, BaseUnit); Info = new QuantityInfo("Angle", new UnitInfo[] @@ -79,7 +75,7 @@ static Angle() new UnitInfo(AngleUnit.Revolution, "Revolutions", BaseUnits.Undefined), new UnitInfo(AngleUnit.Tilt, "Tilt", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Angle); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -93,9 +89,6 @@ static Angle() /// If value is NaN or Infinity. public Angle(double value, AngleUnit unit) { - if (unit == AngleUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -139,24 +132,6 @@ public Angle(double value, UnitSystem unitSystem) /// public static AngleUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Angle - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Angle MaxValue { get; } - - /// - /// Represents the smallest possible value of Angle - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Angle MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Angle quantity. /// @@ -176,6 +151,9 @@ public Angle(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -187,12 +165,6 @@ public Angle(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Angle; - /// /// The of this quantity. /// @@ -377,7 +349,7 @@ public static string GetAbbreviation(AngleUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AngleUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -611,7 +583,7 @@ public static Angle Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Angle Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -642,7 +614,7 @@ public static bool TryParse(string? str, out Angle result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Angle result) { return QuantityParser.Default.TryParse( @@ -670,7 +642,7 @@ public static AngleUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -696,7 +668,7 @@ public static bool TryParseUnit(string str, out AngleUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AngleUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -776,20 +748,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Angle return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Angle left, Angle right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Angle left, Angle right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -805,23 +763,6 @@ public int CompareTo(Angle other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Angle objAngle)) - return false; - - return Equals(objAngle); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Angle other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Angle within the given absolute or relative tolerance. @@ -867,7 +808,7 @@ public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -893,10 +834,9 @@ public override int GetHashCode() public double As(AngleUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -917,10 +857,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AngleUnit unitAsAngleUnit)) + if (!(unit is AngleUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); - return As(unitAsAngleUnit); + return (double)As(typedUnit); } /// @@ -1023,10 +963,10 @@ private bool TryToUnit(AngleUnit unit, out Angle? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AngleUnit unitAsAngleUnit)) + 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(unitAsAngleUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1070,63 +1010,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1208,8 +1114,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AngleUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Angle.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Angle.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs index 74d422b52c..4106feda46 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules. /// [DataContract] - public readonly partial struct ApparentEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ApparentEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ApparentEnergy() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); BaseUnit = ApparentEnergyUnit.VoltampereHour; - MaxValue = new ApparentEnergy(double.MaxValue, BaseUnit); - MinValue = new ApparentEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.ApparentEnergy; - Units = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().Except(new ApparentEnergyUnit[]{ ApparentEnergyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().ToArray(); Zero = new ApparentEnergy(0, BaseUnit); Info = new QuantityInfo("ApparentEnergy", new UnitInfo[] @@ -66,7 +62,7 @@ static ApparentEnergy() new UnitInfo(ApparentEnergyUnit.MegavoltampereHour, "MegavoltampereHours", BaseUnits.Undefined), new UnitInfo(ApparentEnergyUnit.VoltampereHour, "VoltampereHours", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ApparentEnergy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static ApparentEnergy() /// If value is NaN or Infinity. public ApparentEnergy(double value, ApparentEnergyUnit unit) { - if (unit == ApparentEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public ApparentEnergy(double value, UnitSystem unitSystem) /// public static ApparentEnergyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ApparentEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ApparentEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of ApparentEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ApparentEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ApparentEnergy quantity. /// @@ -163,6 +138,9 @@ public ApparentEnergy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public ApparentEnergy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ApparentEnergy; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(ApparentEnergyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ApparentEnergyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static ApparentEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ApparentEnergy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out ApparentEnergy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ApparentEnergy result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static ApparentEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ApparentEnergyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Appar return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ApparentEnergy left, ApparentEnergy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ApparentEnergy left, ApparentEnergy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(ApparentEnergy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ApparentEnergy objApparentEnergy)) - return false; - - return Equals(objApparentEnergy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ApparentEnergy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ApparentEnergy within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(ApparentEnergy other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(ApparentEnergyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ApparentEnergyUnit unitAsApparentEnergyUnit)) + if (!(unit is ApparentEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsApparentEnergyUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(ApparentEnergyUnit unit, out ApparentEnergy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ApparentEnergyUnit unitAsApparentEnergyUnit)) + 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(unitAsApparentEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ApparentEnergyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ApparentEnergy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ApparentEnergy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs index e8a5724ad4..2235f17459 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current. /// [DataContract] - public readonly partial struct ApparentPower : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ApparentPower : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ApparentPower() { BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); BaseUnit = ApparentPowerUnit.Voltampere; - MaxValue = new ApparentPower(double.MaxValue, BaseUnit); - MinValue = new ApparentPower(double.MinValue, BaseUnit); - QuantityType = QuantityType.ApparentPower; - Units = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().Except(new ApparentPowerUnit[]{ ApparentPowerUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().ToArray(); Zero = new ApparentPower(0, BaseUnit); Info = new QuantityInfo("ApparentPower", new UnitInfo[] @@ -67,7 +63,7 @@ static ApparentPower() new UnitInfo(ApparentPowerUnit.Megavoltampere, "Megavoltamperes", BaseUnits.Undefined), new UnitInfo(ApparentPowerUnit.Voltampere, "Voltamperes", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ApparentPower); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static ApparentPower() /// If value is NaN or Infinity. public ApparentPower(double value, ApparentPowerUnit unit) { - if (unit == ApparentPowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public ApparentPower(double value, UnitSystem unitSystem) /// public static ApparentPowerUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ApparentPower - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ApparentPower MaxValue { get; } - - /// - /// Represents the smallest possible value of ApparentPower - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ApparentPower MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ApparentPower quantity. /// @@ -164,6 +139,9 @@ public ApparentPower(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public ApparentPower(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ApparentPower; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(ApparentPowerUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ApparentPowerUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static ApparentPower Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ApparentPower Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out ApparentPower result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ApparentPower result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static ApparentPowerUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out ApparentPowerUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ApparentPowerUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -536,20 +508,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Appar return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ApparentPower left, ApparentPower right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ApparentPower left, ApparentPower right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -565,23 +523,6 @@ public int CompareTo(ApparentPower other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ApparentPower objApparentPower)) - return false; - - return Equals(objApparentPower); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ApparentPower other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ApparentPower within the given absolute or relative tolerance. @@ -627,7 +568,7 @@ public bool Equals(ApparentPower other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -653,10 +594,9 @@ public override int GetHashCode() public double As(ApparentPowerUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -677,10 +617,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ApparentPowerUnit unitAsApparentPowerUnit)) + if (!(unit is ApparentPowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); - return As(unitAsApparentPowerUnit); + return (double)As(typedUnit); } /// @@ -759,10 +699,10 @@ private bool TryToUnit(ApparentPowerUnit unit, out ApparentPower? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ApparentPowerUnit unitAsApparentPowerUnit)) + 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(unitAsApparentPowerUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -806,63 +746,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -944,8 +850,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ApparentPowerUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ApparentPower.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ApparentPower.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index 9342dd182d..c418b69571 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept). /// [DataContract] - public readonly partial struct Area : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Area : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Area() { BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); BaseUnit = AreaUnit.SquareMeter; - MaxValue = new Area(double.MaxValue, BaseUnit); - MinValue = new Area(double.MinValue, BaseUnit); - QuantityType = QuantityType.Area; - Units = Enum.GetValues(typeof(AreaUnit)).Cast().Except(new AreaUnit[]{ AreaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AreaUnit)).Cast().ToArray(); Zero = new Area(0, BaseUnit); Info = new QuantityInfo("Area", new UnitInfo[] @@ -77,7 +73,7 @@ static Area() new UnitInfo(AreaUnit.SquareYard, "SquareYards", new BaseUnits(length: LengthUnit.Yard)), new UnitInfo(AreaUnit.UsSurveySquareFoot, "UsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Area); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -91,9 +87,6 @@ static Area() /// If value is NaN or Infinity. public Area(double value, AreaUnit unit) { - if (unit == AreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -137,24 +130,6 @@ public Area(double value, UnitSystem unitSystem) /// public static AreaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Area - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Area MaxValue { get; } - - /// - /// Represents the smallest possible value of Area - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Area MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Area quantity. /// @@ -174,6 +149,9 @@ public Area(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -185,12 +163,6 @@ public Area(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Area; - /// /// The of this quantity. /// @@ -374,7 +346,7 @@ public static string GetAbbreviation(AreaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AreaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -588,7 +560,7 @@ public static Area Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Area Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -619,7 +591,7 @@ public static bool TryParse(string? str, out Area result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Area result) { return QuantityParser.Default.TryParse( @@ -647,7 +619,7 @@ public static AreaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -673,7 +645,7 @@ public static bool TryParseUnit(string str, out AreaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -753,20 +725,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaU return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Area left, Area right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Area left, Area right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -782,23 +740,6 @@ public int CompareTo(Area other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Area objArea)) - return false; - - return Equals(objArea); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Area other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Area within the given absolute or relative tolerance. @@ -844,7 +785,7 @@ public bool Equals(Area other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -870,10 +811,9 @@ public override int GetHashCode() public double As(AreaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -894,10 +834,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AreaUnit unitAsAreaUnit)) + if (!(unit is AreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); - return As(unitAsAreaUnit); + return (double)As(typedUnit); } /// @@ -996,10 +936,10 @@ private bool TryToUnit(AreaUnit unit, out Area? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AreaUnit unitAsAreaUnit)) + 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(unitAsAreaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1043,63 +983,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1181,8 +1087,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AreaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Area.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Area.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index eb14a0dca0..48b6364f2f 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The area density of a two-dimensional object is calculated as the mass per unit area. For paper this is also called grammage. /// [DataContract] - public readonly partial struct AreaDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct AreaDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static AreaDensity() { BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); BaseUnit = AreaDensityUnit.KilogramPerSquareMeter; - MaxValue = new AreaDensity(double.MaxValue, BaseUnit); - MinValue = new AreaDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.AreaDensity; - Units = Enum.GetValues(typeof(AreaDensityUnit)).Cast().Except(new AreaDensityUnit[]{ AreaDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AreaDensityUnit)).Cast().ToArray(); Zero = new AreaDensity(0, BaseUnit); Info = new QuantityInfo("AreaDensity", new UnitInfo[] @@ -66,7 +62,7 @@ static AreaDensity() new UnitInfo(AreaDensityUnit.KilogramPerSquareMeter, "KilogramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)), new UnitInfo(AreaDensityUnit.MilligramPerSquareMeter, "MilligramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.AreaDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static AreaDensity() /// If value is NaN or Infinity. public AreaDensity(double value, AreaDensityUnit unit) { - if (unit == AreaDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public AreaDensity(double value, UnitSystem unitSystem) /// public static AreaDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of AreaDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AreaDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of AreaDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AreaDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the AreaDensity quantity. /// @@ -163,6 +138,9 @@ public AreaDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public AreaDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.AreaDensity; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(AreaDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AreaDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static AreaDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static AreaDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out AreaDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out AreaDensity result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static AreaDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out AreaDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaD return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(AreaDensity left, AreaDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(AreaDensity left, AreaDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(AreaDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is AreaDensity objAreaDensity)) - return false; - - return Equals(objAreaDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(AreaDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another AreaDensity within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(AreaDensity other, double tolerance, ComparisonType compariso if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(AreaDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AreaDensityUnit unitAsAreaDensityUnit)) + if (!(unit is AreaDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); - return As(unitAsAreaDensityUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(AreaDensityUnit unit, out AreaDensity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AreaDensityUnit unitAsAreaDensityUnit)) + 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(unitAsAreaDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AreaDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return AreaDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return AreaDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index 95ae3ade10..f7900819fc 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A geometric property of an area that reflects how its points are distributed with regard to an axis. /// [DataContract] - public readonly partial struct AreaMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct AreaMomentOfInertia : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static AreaMomentOfInertia() { BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); BaseUnit = AreaMomentOfInertiaUnit.MeterToTheFourth; - MaxValue = new AreaMomentOfInertia(double.MaxValue, BaseUnit); - MinValue = new AreaMomentOfInertia(double.MinValue, BaseUnit); - QuantityType = QuantityType.AreaMomentOfInertia; - Units = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().Except(new AreaMomentOfInertiaUnit[]{ AreaMomentOfInertiaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().ToArray(); Zero = new AreaMomentOfInertia(0, BaseUnit); Info = new QuantityInfo("AreaMomentOfInertia", new UnitInfo[] @@ -69,7 +65,7 @@ static AreaMomentOfInertia() new UnitInfo(AreaMomentOfInertiaUnit.MeterToTheFourth, "MetersToTheFourth", new BaseUnits(length: LengthUnit.Meter)), new UnitInfo(AreaMomentOfInertiaUnit.MillimeterToTheFourth, "MillimetersToTheFourth", new BaseUnits(length: LengthUnit.Millimeter)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.AreaMomentOfInertia); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static AreaMomentOfInertia() /// If value is NaN or Infinity. public AreaMomentOfInertia(double value, AreaMomentOfInertiaUnit unit) { - if (unit == AreaMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) /// public static AreaMomentOfInertiaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of AreaMomentOfInertia - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AreaMomentOfInertia MaxValue { get; } - - /// - /// Represents the smallest possible value of AreaMomentOfInertia - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static AreaMomentOfInertia MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the AreaMomentOfInertia quantity. /// @@ -166,6 +141,9 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.AreaMomentOfInertia; - /// /// The of this quantity. /// @@ -275,7 +247,7 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -409,7 +381,7 @@ public static AreaMomentOfInertia Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static AreaMomentOfInertia Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -440,7 +412,7 @@ public static bool TryParse(string? str, out AreaMomentOfInertia result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out AreaMomentOfInertia result) { return QuantityParser.Default.TryParse( @@ -468,7 +440,7 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -494,7 +466,7 @@ public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaMomentOfInertiaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -574,20 +546,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaM return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -603,23 +561,6 @@ public int CompareTo(AreaMomentOfInertia other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is AreaMomentOfInertia objAreaMomentOfInertia)) - return false; - - return Equals(objAreaMomentOfInertia); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(AreaMomentOfInertia other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another AreaMomentOfInertia within the given absolute or relative tolerance. @@ -665,7 +606,7 @@ public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -691,10 +632,9 @@ public override int GetHashCode() public double As(AreaMomentOfInertiaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -715,10 +655,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is AreaMomentOfInertiaUnit unitAsAreaMomentOfInertiaUnit)) + if (!(unit is AreaMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); - return As(unitAsAreaMomentOfInertiaUnit); + return (double)As(typedUnit); } /// @@ -801,10 +741,10 @@ private bool TryToUnit(AreaMomentOfInertiaUnit unit, out AreaMomentOfInertia? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is AreaMomentOfInertiaUnit unitAsAreaMomentOfInertiaUnit)) + 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(unitAsAreaMomentOfInertiaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -848,63 +788,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -986,8 +892,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(AreaMomentOfInertiaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return AreaMomentOfInertia.QuantityType; else if (conversionType == typeof(QuantityInfo)) return AreaMomentOfInertia.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index 0535dff037..5eb7072ec3 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Bit_rate /// [DataContract] - public readonly partial struct BitRate : IQuantity, IDecimalQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct BitRate : IQuantity, IDecimalQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static BitRate() { BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); BaseUnit = BitRateUnit.BitPerSecond; - MaxValue = new BitRate(decimal.MaxValue, BaseUnit); - MinValue = new BitRate(decimal.MinValue, BaseUnit); - QuantityType = QuantityType.BitRate; - Units = Enum.GetValues(typeof(BitRateUnit)).Cast().Except(new BitRateUnit[]{ BitRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(BitRateUnit)).Cast().ToArray(); Zero = new BitRate(0, BaseUnit); Info = new QuantityInfo("BitRate", new UnitInfo[] @@ -92,7 +88,7 @@ static BitRate() new UnitInfo(BitRateUnit.TerabitPerSecond, "TerabitsPerSecond", BaseUnits.Undefined), new UnitInfo(BitRateUnit.TerabytePerSecond, "TerabytesPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.BitRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -106,9 +102,6 @@ static BitRate() /// If value is NaN or Infinity. public BitRate(decimal value, BitRateUnit unit) { - if (unit == BitRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = value; _unit = unit; } @@ -152,24 +145,6 @@ public BitRate(decimal value, UnitSystem unitSystem) /// public static BitRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of BitRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static BitRate MaxValue { get; } - - /// - /// Represents the smallest possible value of BitRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static BitRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the BitRate quantity. /// @@ -189,7 +164,8 @@ public BitRate(decimal value, UnitSystem unitSystem) /// public decimal Value => _value; - double IQuantity.Value => (double) _value; + /// + QuantityValue IQuantity.Value => _value; /// decimal IDecimalQuantity.Value => _value; @@ -205,12 +181,6 @@ public BitRate(decimal value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.BitRate; - /// /// The of this quantity. /// @@ -221,134 +191,134 @@ public BitRate(decimal value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BitsPerSecond => As(BitRateUnit.BitPerSecond); + public decimal BitsPerSecond => As(BitRateUnit.BitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BytesPerSecond => As(BitRateUnit.BytePerSecond); + public decimal BytesPerSecond => As(BitRateUnit.BytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); + public decimal ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); + public decimal ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); + public decimal ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); + public decimal ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); + public decimal GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); + public decimal GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); + public decimal GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); + public decimal GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); + public decimal KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); + public decimal KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); + public decimal KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); + public decimal KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); + public decimal MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); + public decimal MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); + public decimal MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); + public decimal MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); + public decimal PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); + public decimal PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); + public decimal PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); + public decimal PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); + public decimal TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); + public decimal TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); + public decimal TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); + public decimal TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); #endregion @@ -463,7 +433,7 @@ public static string GetAbbreviation(BitRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(BitRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -797,7 +767,7 @@ public static BitRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static BitRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -828,7 +798,7 @@ public static bool TryParse(string? str, out BitRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out BitRate result) { return QuantityParser.Default.TryParse( @@ -856,7 +826,7 @@ public static BitRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -882,7 +852,7 @@ public static bool TryParseUnit(string str, out BitRateUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out BitRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -929,7 +899,7 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out BitRa } /// Get ratio value from dividing by . - public static double operator /(BitRate left, BitRate right) + public static decimal operator /(BitRate left, BitRate right) { return left.BitsPerSecond / right.BitsPerSecond; } @@ -962,20 +932,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out BitRa return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(BitRate left, BitRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(BitRate left, BitRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -991,23 +947,6 @@ public int CompareTo(BitRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is BitRate objBitRate)) - return false; - - return Equals(objBitRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(BitRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another BitRate within the given absolute or relative tolerance. @@ -1048,13 +987,13 @@ public bool Equals(BitRate other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(BitRate other, double tolerance, ComparisonType comparisonType) + 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."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + decimal thisValue = this.Value; + decimal otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1076,17 +1015,21 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(BitRateUnit unit) + public decimal As(BitRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; + + return ToUnit(unit).Value; + } - var converted = ToUnit(unit); - return (double)converted.Value; + double IQuantity.As(BitRateUnit unit) + { + return (double)As(unit); } /// - public double As(UnitSystem unitSystem) + public decimal As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1100,13 +1043,19 @@ public double As(UnitSystem unitSystem) return As(firstUnitInfo.Value); } + /// + double IQuantity.As(UnitSystem unitSystem) + { + return (double)As(unitSystem); + } + /// double IQuantity.As(Enum unit) { - if (!(unit is BitRateUnit unitAsBitRateUnit)) + if (!(unit is BitRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); - return As(unitAsBitRateUnit); + return (double)As(typedUnit); } /// @@ -1229,10 +1178,10 @@ private bool TryToUnit(BitRateUnit unit, out BitRate? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is BitRateUnit unitAsBitRateUnit)) + 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(unitAsBitRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1276,63 +1225,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1414,8 +1329,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(BitRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return BitRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return BitRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 60e8a136a4..e62ed04a01 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output. /// [DataContract] - public readonly partial struct BrakeSpecificFuelConsumption : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct BrakeSpecificFuelConsumption : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static BrakeSpecificFuelConsumption() { BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); BaseUnit = BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; - MaxValue = new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); - MinValue = new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); - QuantityType = QuantityType.BrakeSpecificFuelConsumption; - Units = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().Except(new BrakeSpecificFuelConsumptionUnit[]{ BrakeSpecificFuelConsumptionUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().ToArray(); Zero = new BrakeSpecificFuelConsumption(0, BaseUnit); Info = new QuantityInfo("BrakeSpecificFuelConsumption", new UnitInfo[] @@ -66,7 +62,7 @@ static BrakeSpecificFuelConsumption() new UnitInfo(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, "KilogramsPerJoule", BaseUnits.Undefined), new UnitInfo(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "PoundsPerMechanicalHorsepowerHour", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.BrakeSpecificFuelConsumption); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static BrakeSpecificFuelConsumption() /// If value is NaN or Infinity. public BrakeSpecificFuelConsumption(double value, BrakeSpecificFuelConsumptionUnit unit) { - if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) /// public static BrakeSpecificFuelConsumptionUnit BaseUnit { get; } - /// - /// Represents the largest possible value of BrakeSpecificFuelConsumption - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static BrakeSpecificFuelConsumption MaxValue { get; } - - /// - /// Represents the smallest possible value of BrakeSpecificFuelConsumption - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static BrakeSpecificFuelConsumption MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the BrakeSpecificFuelConsumption quantity. /// @@ -163,6 +138,9 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.BrakeSpecificFuelConsumption; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static BrakeSpecificFuelConsumption Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static BrakeSpecificFuelConsumption Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out BrakeSpecificFuelConsumption result /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out BrakeSpecificFuelConsumption result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out BrakeSpecificFuelConsumptionUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Brake return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(BrakeSpecificFuelConsumption other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is BrakeSpecificFuelConsumption objBrakeSpecificFuelConsumption)) - return false; - - return Equals(objBrakeSpecificFuelConsumption); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(BrakeSpecificFuelConsumption other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another BrakeSpecificFuelConsumption within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, Compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(BrakeSpecificFuelConsumptionUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is BrakeSpecificFuelConsumptionUnit unitAsBrakeSpecificFuelConsumptionUnit)) + if (!(unit is BrakeSpecificFuelConsumptionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return As(unitAsBrakeSpecificFuelConsumptionUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(BrakeSpecificFuelConsumptionUnit unit, out BrakeSpecificF /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is BrakeSpecificFuelConsumptionUnit unitAsBrakeSpecificFuelConsumptionUnit)) + 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(unitAsBrakeSpecificFuelConsumptionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(BrakeSpecificFuelConsumptionUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return BrakeSpecificFuelConsumption.QuantityType; else if (conversionType == typeof(QuantityInfo)) return BrakeSpecificFuelConsumption.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs index e4a273ba9f..cc5c707328 100644 --- a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Capacitance /// [DataContract] - public readonly partial struct Capacitance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Capacitance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Capacitance() { BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); BaseUnit = CapacitanceUnit.Farad; - MaxValue = new Capacitance(double.MaxValue, BaseUnit); - MinValue = new Capacitance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Capacitance; - Units = Enum.GetValues(typeof(CapacitanceUnit)).Cast().Except(new CapacitanceUnit[]{ CapacitanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(CapacitanceUnit)).Cast().ToArray(); Zero = new Capacitance(0, BaseUnit); Info = new QuantityInfo("Capacitance", new UnitInfo[] @@ -73,7 +69,7 @@ static Capacitance() new UnitInfo(CapacitanceUnit.Nanofarad, "Nanofarads", BaseUnits.Undefined), new UnitInfo(CapacitanceUnit.Picofarad, "Picofarads", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Capacitance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -87,9 +83,6 @@ static Capacitance() /// If value is NaN or Infinity. public Capacitance(double value, CapacitanceUnit unit) { - if (unit == CapacitanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -133,24 +126,6 @@ public Capacitance(double value, UnitSystem unitSystem) /// public static CapacitanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Capacitance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Capacitance MaxValue { get; } - - /// - /// Represents the smallest possible value of Capacitance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Capacitance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Capacitance quantity. /// @@ -170,6 +145,9 @@ public Capacitance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -181,12 +159,6 @@ public Capacitance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Capacitance; - /// /// The of this quantity. /// @@ -287,7 +259,7 @@ public static string GetAbbreviation(CapacitanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(CapacitanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -431,7 +403,7 @@ public static Capacitance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Capacitance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -462,7 +434,7 @@ public static bool TryParse(string? str, out Capacitance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Capacitance result) { return QuantityParser.Default.TryParse( @@ -490,7 +462,7 @@ public static CapacitanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -516,7 +488,7 @@ public static bool TryParseUnit(string str, out CapacitanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out CapacitanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -596,20 +568,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Capac return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Capacitance left, Capacitance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Capacitance left, Capacitance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -625,23 +583,6 @@ public int CompareTo(Capacitance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Capacitance objCapacitance)) - return false; - - return Equals(objCapacitance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Capacitance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Capacitance within the given absolute or relative tolerance. @@ -687,7 +628,7 @@ public bool Equals(Capacitance other, double tolerance, ComparisonType compariso if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -713,10 +654,9 @@ public override int GetHashCode() public double As(CapacitanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -737,10 +677,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is CapacitanceUnit unitAsCapacitanceUnit)) + if (!(unit is CapacitanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); - return As(unitAsCapacitanceUnit); + return (double)As(typedUnit); } /// @@ -825,10 +765,10 @@ private bool TryToUnit(CapacitanceUnit unit, out Capacitance? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is CapacitanceUnit unitAsCapacitanceUnit)) + 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(unitAsCapacitanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -872,63 +812,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1010,8 +916,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(CapacitanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Capacitance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Capacitance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index 93938bd458..aec2f603df 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A unit that represents a fractional change in size in response to a change in temperature. /// [DataContract] - public readonly partial struct CoefficientOfThermalExpansion : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct CoefficientOfThermalExpansion : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static CoefficientOfThermalExpansion() { BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); BaseUnit = CoefficientOfThermalExpansionUnit.InverseKelvin; - MaxValue = new CoefficientOfThermalExpansion(double.MaxValue, BaseUnit); - MinValue = new CoefficientOfThermalExpansion(double.MinValue, BaseUnit); - QuantityType = QuantityType.CoefficientOfThermalExpansion; - Units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().Except(new CoefficientOfThermalExpansionUnit[]{ CoefficientOfThermalExpansionUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().ToArray(); Zero = new CoefficientOfThermalExpansion(0, BaseUnit); Info = new QuantityInfo("CoefficientOfThermalExpansion", new UnitInfo[] @@ -66,7 +62,7 @@ static CoefficientOfThermalExpansion() new UnitInfo(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, "InverseDegreeFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)), new UnitInfo(CoefficientOfThermalExpansionUnit.InverseKelvin, "InverseKelvin", new BaseUnits(temperature: TemperatureUnit.Kelvin)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.CoefficientOfThermalExpansion); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static CoefficientOfThermalExpansion() /// If value is NaN or Infinity. public CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansionUnit unit) { - if (unit == CoefficientOfThermalExpansionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) /// public static CoefficientOfThermalExpansionUnit BaseUnit { get; } - /// - /// Represents the largest possible value of CoefficientOfThermalExpansion - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static CoefficientOfThermalExpansion MaxValue { get; } - - /// - /// Represents the smallest possible value of CoefficientOfThermalExpansion - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static CoefficientOfThermalExpansion MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the CoefficientOfThermalExpansion quantity. /// @@ -163,6 +138,9 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.CoefficientOfThermalExpansion; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static CoefficientOfThermalExpansion Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static CoefficientOfThermalExpansion Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out CoefficientOfThermalExpansion resul /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out CoefficientOfThermalExpansion result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static CoefficientOfThermalExpansionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUni /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out CoefficientOfThermalExpansionUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Coeff return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(CoefficientOfThermalExpansion other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is CoefficientOfThermalExpansion objCoefficientOfThermalExpansion)) - return false; - - return Equals(objCoefficientOfThermalExpansion); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(CoefficientOfThermalExpansion other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another CoefficientOfThermalExpansion within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(CoefficientOfThermalExpansion other, double tolerance, Compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(CoefficientOfThermalExpansionUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit)) + if (!(unit is CoefficientOfThermalExpansionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); - return As(unitAsCoefficientOfThermalExpansionUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(CoefficientOfThermalExpansionUnit unit, out CoefficientOf /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is CoefficientOfThermalExpansionUnit unitAsCoefficientOfThermalExpansionUnit)) + 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(unitAsCoefficientOfThermalExpansionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(CoefficientOfThermalExpansionUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return CoefficientOfThermalExpansion.QuantityType; else if (conversionType == typeof(QuantityInfo)) return CoefficientOfThermalExpansion.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs index ea9938025b..2124d195a9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,10 +32,10 @@ namespace UnitsNet { /// /// - /// Compressibility is the measure of the relative volume change of a fluid or solid in response to pressure changes. + /// /// [DataContract] - public readonly partial struct Compressibility : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Compressibility : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Compressibility() { BaseDimensions = new BaseDimensions(1, -1, 2, 0, 0, 0, 0); BaseUnit = CompressibilityUnit.InversePascal; - MaxValue = new Compressibility(double.MaxValue, BaseUnit); - MinValue = new Compressibility(double.MinValue, BaseUnit); - QuantityType = QuantityType.Compressibility; - Units = Enum.GetValues(typeof(CompressibilityUnit)).Cast().Except(new CompressibilityUnit[]{ CompressibilityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(CompressibilityUnit)).Cast().ToArray(); Zero = new Compressibility(0, BaseUnit); Info = new QuantityInfo("Compressibility", new UnitInfo[] @@ -70,7 +66,7 @@ static Compressibility() new UnitInfo(CompressibilityUnit.InversePascal, "InversePascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), new UnitInfo(CompressibilityUnit.InversePoundForcePerSquareInch, "InversePoundsForcePerSquareInch", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Compressibility); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static Compressibility() /// If value is NaN or Infinity. public Compressibility(double value, CompressibilityUnit unit) { - if (unit == CompressibilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public Compressibility(double value, UnitSystem unitSystem) /// public static CompressibilityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Compressibility - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Compressibility MaxValue { get; } - - /// - /// Represents the smallest possible value of Compressibility - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Compressibility MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Compressibility quantity. /// @@ -167,6 +142,9 @@ public Compressibility(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public Compressibility(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Compressibility; - /// /// The of this quantity. /// @@ -284,7 +256,7 @@ public static string GetAbbreviation(CompressibilityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(CompressibilityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -428,7 +400,7 @@ public static Compressibility Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Compressibility Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -459,7 +431,7 @@ public static bool TryParse(string? str, out Compressibility result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Compressibility result) { return QuantityParser.Default.TryParse( @@ -487,7 +459,7 @@ public static CompressibilityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -513,7 +485,7 @@ public static bool TryParseUnit(string str, out CompressibilityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out CompressibilityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -593,20 +565,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Compr return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Compressibility left, Compressibility right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Compressibility left, Compressibility right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -622,23 +580,6 @@ public int CompareTo(Compressibility other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Compressibility objCompressibility)) - return false; - - return Equals(objCompressibility); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Compressibility other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Compressibility within the given absolute or relative tolerance. @@ -684,7 +625,7 @@ public bool Equals(Compressibility other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -710,10 +651,9 @@ public override int GetHashCode() public double As(CompressibilityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -734,10 +674,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is CompressibilityUnit unitAsCompressibilityUnit)) + if (!(unit is CompressibilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} is supported.", nameof(unit)); - return As(unitAsCompressibilityUnit); + return (double)As(typedUnit); } /// @@ -822,10 +762,10 @@ private bool TryToUnit(CompressibilityUnit unit, out Compressibility? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is CompressibilityUnit unitAsCompressibilityUnit)) + 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(unitAsCompressibilityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -869,63 +809,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1007,8 +913,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(CompressibilityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Compressibility.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Compressibility.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 2eae36065b..f8e69b636d 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Density /// [DataContract] - public readonly partial struct Density : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Density : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Density() { BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); BaseUnit = DensityUnit.KilogramPerCubicMeter; - MaxValue = new Density(double.MaxValue, BaseUnit); - MinValue = new Density(double.MinValue, BaseUnit); - QuantityType = QuantityType.Density; - Units = Enum.GetValues(typeof(DensityUnit)).Cast().Except(new DensityUnit[]{ DensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(DensityUnit)).Cast().ToArray(); Zero = new Density(0, BaseUnit); Info = new QuantityInfo("Density", new UnitInfo[] @@ -117,7 +113,7 @@ static Density() new UnitInfo(DensityUnit.TonnePerCubicMeter, "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)), new UnitInfo(DensityUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Density); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -131,9 +127,6 @@ static Density() /// If value is NaN or Infinity. public Density(double value, DensityUnit unit) { - if (unit == DensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -177,24 +170,6 @@ public Density(double value, UnitSystem unitSystem) /// public static DensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Density - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Density MaxValue { get; } - - /// - /// Represents the smallest possible value of Density - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Density MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Density quantity. /// @@ -214,6 +189,9 @@ public Density(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -225,12 +203,6 @@ public Density(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Density; - /// /// The of this quantity. /// @@ -687,7 +659,7 @@ public static string GetAbbreviation(DensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(DensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1271,7 +1243,7 @@ public static Density Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Density Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1302,7 +1274,7 @@ public static bool TryParse(string? str, out Density result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Density result) { return QuantityParser.Default.TryParse( @@ -1330,7 +1302,7 @@ public static DensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1356,7 +1328,7 @@ public static bool TryParseUnit(string str, out DensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out DensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1436,20 +1408,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Densi return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Density left, Density right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Density left, Density right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1465,23 +1423,6 @@ public int CompareTo(Density other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Density objDensity)) - return false; - - return Equals(objDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Density other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Density within the given absolute or relative tolerance. @@ -1527,7 +1468,7 @@ public bool Equals(Density other, double tolerance, ComparisonType comparisonTyp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1553,10 +1494,9 @@ public override int GetHashCode() public double As(DensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1577,10 +1517,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is DensityUnit unitAsDensityUnit)) + if (!(unit is DensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); - return As(unitAsDensityUnit); + return (double)As(typedUnit); } /// @@ -1753,10 +1693,10 @@ private bool TryToUnit(DensityUnit unit, out Density? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is DensityUnit unitAsDensityUnit)) + 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(unitAsDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1800,63 +1740,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1938,8 +1844,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(DensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Density.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Density.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index 16b65fbe4a..8fe54fb0d9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them. /// [DataContract] - public readonly partial struct Duration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Duration : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Duration() { BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); BaseUnit = DurationUnit.Second; - MaxValue = new Duration(double.MaxValue, BaseUnit); - MinValue = new Duration(double.MinValue, BaseUnit); - QuantityType = QuantityType.Duration; - Units = Enum.GetValues(typeof(DurationUnit)).Cast().Except(new DurationUnit[]{ DurationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(DurationUnit)).Cast().ToArray(); Zero = new Duration(0, BaseUnit); Info = new QuantityInfo("Duration", new UnitInfo[] @@ -74,7 +70,7 @@ static Duration() new UnitInfo(DurationUnit.Week, "Weeks", new BaseUnits(time: DurationUnit.Week)), new UnitInfo(DurationUnit.Year365, "Years365", new BaseUnits(time: DurationUnit.Year365)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Duration); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -88,9 +84,6 @@ static Duration() /// If value is NaN or Infinity. public Duration(double value, DurationUnit unit) { - if (unit == DurationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -134,24 +127,6 @@ public Duration(double value, UnitSystem unitSystem) /// public static DurationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Duration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Duration MaxValue { get; } - - /// - /// Represents the smallest possible value of Duration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Duration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Duration quantity. /// @@ -171,6 +146,9 @@ public Duration(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -182,12 +160,6 @@ public Duration(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Duration; - /// /// The of this quantity. /// @@ -330,7 +302,7 @@ public static string GetAbbreviation(DurationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(DurationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -514,7 +486,7 @@ public static Duration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Duration Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -545,7 +517,7 @@ public static bool TryParse(string? str, out Duration result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Duration result) { return QuantityParser.Default.TryParse( @@ -573,7 +545,7 @@ public static DurationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -599,7 +571,7 @@ public static bool TryParseUnit(string str, out DurationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out DurationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -679,20 +651,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Durat return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Duration left, Duration right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Duration left, Duration right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -708,23 +666,6 @@ public int CompareTo(Duration other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Duration objDuration)) - return false; - - return Equals(objDuration); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Duration other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Duration within the given absolute or relative tolerance. @@ -770,7 +711,7 @@ public bool Equals(Duration other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -796,10 +737,9 @@ public override int GetHashCode() public double As(DurationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -820,10 +760,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is DurationUnit unitAsDurationUnit)) + if (!(unit is DurationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); - return As(unitAsDurationUnit); + return (double)As(typedUnit); } /// @@ -916,10 +856,10 @@ private bool TryToUnit(DurationUnit unit, out Duration? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is DurationUnit unitAsDurationUnit)) + 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(unitAsDurationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -963,63 +903,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1101,8 +1007,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(DurationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Duration.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Duration.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index ba559a2587..c402327701 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity /// [DataContract] - public readonly partial struct DynamicViscosity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct DynamicViscosity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static DynamicViscosity() { BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); BaseUnit = DynamicViscosityUnit.NewtonSecondPerMeterSquared; - MaxValue = new DynamicViscosity(double.MaxValue, BaseUnit); - MinValue = new DynamicViscosity(double.MinValue, BaseUnit); - QuantityType = QuantityType.DynamicViscosity; - Units = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().Except(new DynamicViscosityUnit[]{ DynamicViscosityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().ToArray(); Zero = new DynamicViscosity(0, BaseUnit); Info = new QuantityInfo("DynamicViscosity", new UnitInfo[] @@ -76,7 +72,7 @@ static DynamicViscosity() new UnitInfo(DynamicViscosityUnit.PoundPerFootSecond, "PoundsPerFootSecond", BaseUnits.Undefined), new UnitInfo(DynamicViscosityUnit.Reyn, "Reyns", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.DynamicViscosity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -90,9 +86,6 @@ static DynamicViscosity() /// If value is NaN or Infinity. public DynamicViscosity(double value, DynamicViscosityUnit unit) { - if (unit == DynamicViscosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -136,24 +129,6 @@ public DynamicViscosity(double value, UnitSystem unitSystem) /// public static DynamicViscosityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of DynamicViscosity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static DynamicViscosity MaxValue { get; } - - /// - /// Represents the smallest possible value of DynamicViscosity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static DynamicViscosity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the DynamicViscosity quantity. /// @@ -173,6 +148,9 @@ public DynamicViscosity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -184,12 +162,6 @@ public DynamicViscosity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.DynamicViscosity; - /// /// The of this quantity. /// @@ -314,7 +286,7 @@ public static string GetAbbreviation(DynamicViscosityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(DynamicViscosityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -488,7 +460,7 @@ public static DynamicViscosity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static DynamicViscosity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -519,7 +491,7 @@ public static bool TryParse(string? str, out DynamicViscosity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out DynamicViscosity result) { return QuantityParser.Default.TryParse( @@ -547,7 +519,7 @@ public static DynamicViscosityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -573,7 +545,7 @@ public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out DynamicViscosityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -653,20 +625,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Dynam return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(DynamicViscosity left, DynamicViscosity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(DynamicViscosity left, DynamicViscosity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -682,23 +640,6 @@ public int CompareTo(DynamicViscosity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is DynamicViscosity objDynamicViscosity)) - return false; - - return Equals(objDynamicViscosity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(DynamicViscosity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another DynamicViscosity within the given absolute or relative tolerance. @@ -744,7 +685,7 @@ public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -770,10 +711,9 @@ public override int GetHashCode() public double As(DynamicViscosityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -794,10 +734,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is DynamicViscosityUnit unitAsDynamicViscosityUnit)) + if (!(unit is DynamicViscosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); - return As(unitAsDynamicViscosityUnit); + return (double)As(typedUnit); } /// @@ -888,10 +828,10 @@ private bool TryToUnit(DynamicViscosityUnit unit, out DynamicViscosity? converte /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is DynamicViscosityUnit unitAsDynamicViscosityUnit)) + 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(unitAsDynamicViscosityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -935,63 +875,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1073,8 +979,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(DynamicViscosityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return DynamicViscosity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return DynamicViscosity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index e3653100e3..702e7d9b4d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S). /// [DataContract] - public readonly partial struct ElectricAdmittance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricAdmittance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricAdmittance() { BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); BaseUnit = ElectricAdmittanceUnit.Siemens; - MaxValue = new ElectricAdmittance(double.MaxValue, BaseUnit); - MinValue = new ElectricAdmittance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricAdmittance; - Units = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().Except(new ElectricAdmittanceUnit[]{ ElectricAdmittanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().ToArray(); Zero = new ElectricAdmittance(0, BaseUnit); Info = new QuantityInfo("ElectricAdmittance", new UnitInfo[] @@ -67,7 +63,7 @@ static ElectricAdmittance() new UnitInfo(ElectricAdmittanceUnit.Nanosiemens, "Nanosiemens", BaseUnits.Undefined), new UnitInfo(ElectricAdmittanceUnit.Siemens, "Siemens", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricAdmittance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static ElectricAdmittance() /// If value is NaN or Infinity. public ElectricAdmittance(double value, ElectricAdmittanceUnit unit) { - if (unit == ElectricAdmittanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) /// public static ElectricAdmittanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricAdmittance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricAdmittance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricAdmittance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricAdmittance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricAdmittance quantity. /// @@ -164,6 +139,9 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricAdmittance; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricAdmittanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static ElectricAdmittance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricAdmittance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out ElectricAdmittance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricAdmittance result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static ElectricAdmittanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricAdmittanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -536,20 +508,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -565,23 +523,6 @@ public int CompareTo(ElectricAdmittance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricAdmittance objElectricAdmittance)) - return false; - - return Equals(objElectricAdmittance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricAdmittance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricAdmittance within the given absolute or relative tolerance. @@ -627,7 +568,7 @@ public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -653,10 +594,9 @@ public override int GetHashCode() public double As(ElectricAdmittanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -677,10 +617,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricAdmittanceUnit unitAsElectricAdmittanceUnit)) + if (!(unit is ElectricAdmittanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricAdmittanceUnit); + return (double)As(typedUnit); } /// @@ -759,10 +699,10 @@ private bool TryToUnit(ElectricAdmittanceUnit unit, out ElectricAdmittance? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricAdmittanceUnit unitAsElectricAdmittanceUnit)) + 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(unitAsElectricAdmittanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -806,63 +746,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -944,8 +850,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricAdmittanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricAdmittance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricAdmittance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index c76de84c2d..ec762d9d56 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electric_charge /// [DataContract] - public readonly partial struct ElectricCharge : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricCharge : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricCharge() { BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); BaseUnit = ElectricChargeUnit.Coulomb; - MaxValue = new ElectricCharge(double.MaxValue, BaseUnit); - MinValue = new ElectricCharge(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCharge; - Units = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().Except(new ElectricChargeUnit[]{ ElectricChargeUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().ToArray(); Zero = new ElectricCharge(0, BaseUnit); Info = new QuantityInfo("ElectricCharge", new UnitInfo[] @@ -71,7 +67,7 @@ static ElectricCharge() new UnitInfo(ElectricChargeUnit.MegaampereHour, "MegaampereHours", BaseUnits.Undefined), new UnitInfo(ElectricChargeUnit.MilliampereHour, "MilliampereHours", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCharge); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -85,9 +81,6 @@ static ElectricCharge() /// If value is NaN or Infinity. public ElectricCharge(double value, ElectricChargeUnit unit) { - if (unit == ElectricChargeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -131,24 +124,6 @@ public ElectricCharge(double value, UnitSystem unitSystem) /// public static ElectricChargeUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricCharge - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCharge MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCharge - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCharge MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricCharge quantity. /// @@ -168,6 +143,9 @@ public ElectricCharge(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -179,12 +157,6 @@ public ElectricCharge(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricCharge; - /// /// The of this quantity. /// @@ -269,7 +241,7 @@ public static string GetAbbreviation(ElectricChargeUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricChargeUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -393,7 +365,7 @@ public static ElectricCharge Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCharge Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -424,7 +396,7 @@ public static bool TryParse(string? str, out ElectricCharge result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCharge result) { return QuantityParser.Default.TryParse( @@ -452,7 +424,7 @@ public static ElectricChargeUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -478,7 +450,7 @@ public static bool TryParseUnit(string str, out ElectricChargeUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricChargeUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -558,20 +530,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricCharge left, ElectricCharge right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricCharge left, ElectricCharge right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -587,23 +545,6 @@ public int CompareTo(ElectricCharge other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCharge objElectricCharge)) - return false; - - return Equals(objElectricCharge); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricCharge other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricCharge within the given absolute or relative tolerance. @@ -649,7 +590,7 @@ public bool Equals(ElectricCharge other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -675,10 +616,9 @@ public override int GetHashCode() public double As(ElectricChargeUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -699,10 +639,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricChargeUnit unitAsElectricChargeUnit)) + if (!(unit is ElectricChargeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); - return As(unitAsElectricChargeUnit); + return (double)As(typedUnit); } /// @@ -783,10 +723,10 @@ private bool TryToUnit(ElectricChargeUnit unit, out ElectricCharge? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricChargeUnit unitAsElectricChargeUnit)) + 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(unitAsElectricChargeUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -830,63 +770,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -968,8 +874,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricChargeUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricCharge.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricCharge.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index 7129dba15d..b9964274b8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Charge_density /// [DataContract] - public readonly partial struct ElectricChargeDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricChargeDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static ElectricChargeDensity() { BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); BaseUnit = ElectricChargeDensityUnit.CoulombPerCubicMeter; - MaxValue = new ElectricChargeDensity(double.MaxValue, BaseUnit); - MinValue = new ElectricChargeDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricChargeDensity; - Units = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().Except(new ElectricChargeDensityUnit[]{ ElectricChargeDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().ToArray(); Zero = new ElectricChargeDensity(0, BaseUnit); Info = new QuantityInfo("ElectricChargeDensity", new UnitInfo[] { new UnitInfo(ElectricChargeDensityUnit.CoulombPerCubicMeter, "CoulombsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricChargeDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static ElectricChargeDensity() /// If value is NaN or Infinity. public ElectricChargeDensity(double value, ElectricChargeDensityUnit unit) { - if (unit == ElectricChargeDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) /// public static ElectricChargeDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricChargeDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricChargeDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricChargeDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricChargeDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricChargeDensity quantity. /// @@ -164,6 +139,9 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricChargeDensity; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricChargeDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static ElectricChargeDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricChargeDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out ElectricChargeDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricChargeDensity result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static ElectricChargeDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricChargeDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(ElectricChargeDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricChargeDensity objElectricChargeDensity)) - return false; - - return Equals(objElectricChargeDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricChargeDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricChargeDensity within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(ElectricChargeDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricChargeDensityUnit unitAsElectricChargeDensityUnit)) + if (!(unit is ElectricChargeDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricChargeDensityUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(ElectricChargeDensityUnit unit, out ElectricChargeDensity /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricChargeDensityUnit unitAsElectricChargeDensityUnit)) + 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(unitAsElectricChargeDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricChargeDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricChargeDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricChargeDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index ca0bbe3348..5c1e46b7f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance /// [DataContract] - public readonly partial struct ElectricConductance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricConductance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricConductance() { BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); BaseUnit = ElectricConductanceUnit.Siemens; - MaxValue = new ElectricConductance(double.MaxValue, BaseUnit); - MinValue = new ElectricConductance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricConductance; - Units = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().Except(new ElectricConductanceUnit[]{ ElectricConductanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().ToArray(); Zero = new ElectricConductance(0, BaseUnit); Info = new QuantityInfo("ElectricConductance", new UnitInfo[] @@ -69,7 +65,7 @@ static ElectricConductance() new UnitInfo(ElectricConductanceUnit.Millisiemens, "Millisiemens", BaseUnits.Undefined), new UnitInfo(ElectricConductanceUnit.Siemens, "Siemens", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricConductance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static ElectricConductance() /// If value is NaN or Infinity. public ElectricConductance(double value, ElectricConductanceUnit unit) { - if (unit == ElectricConductanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public ElectricConductance(double value, UnitSystem unitSystem) /// public static ElectricConductanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricConductance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricConductance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricConductance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricConductance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricConductance quantity. /// @@ -166,6 +141,9 @@ public ElectricConductance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public ElectricConductance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricConductance; - /// /// The of this quantity. /// @@ -251,7 +223,7 @@ public static string GetAbbreviation(ElectricConductanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricConductanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -355,7 +327,7 @@ public static ElectricConductance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricConductance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -386,7 +358,7 @@ public static bool TryParse(string? str, out ElectricConductance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricConductance result) { return QuantityParser.Default.TryParse( @@ -414,7 +386,7 @@ public static ElectricConductanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -440,7 +412,7 @@ public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricConductanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -520,20 +492,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricConductance left, ElectricConductance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricConductance left, ElectricConductance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -549,23 +507,6 @@ public int CompareTo(ElectricConductance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricConductance objElectricConductance)) - return false; - - return Equals(objElectricConductance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricConductance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricConductance within the given absolute or relative tolerance. @@ -611,7 +552,7 @@ public bool Equals(ElectricConductance other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -637,10 +578,9 @@ public override int GetHashCode() public double As(ElectricConductanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -661,10 +601,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricConductanceUnit unitAsElectricConductanceUnit)) + if (!(unit is ElectricConductanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricConductanceUnit); + return (double)As(typedUnit); } /// @@ -741,10 +681,10 @@ private bool TryToUnit(ElectricConductanceUnit unit, out ElectricConductance? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricConductanceUnit unitAsElectricConductanceUnit)) + 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(unitAsElectricConductanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -788,63 +728,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -926,8 +832,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricConductanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricConductance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricConductance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index f227dd1f7d..9398bb6d6a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity /// [DataContract] - public readonly partial struct ElectricConductivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricConductivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricConductivity() { BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); BaseUnit = ElectricConductivityUnit.SiemensPerMeter; - MaxValue = new ElectricConductivity(double.MaxValue, BaseUnit); - MinValue = new ElectricConductivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricConductivity; - Units = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().Except(new ElectricConductivityUnit[]{ ElectricConductivityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().ToArray(); Zero = new ElectricConductivity(0, BaseUnit); Info = new QuantityInfo("ElectricConductivity", new UnitInfo[] @@ -72,7 +68,7 @@ static ElectricConductivity() new UnitInfo(ElectricConductivityUnit.SiemensPerInch, "SiemensPerInch", BaseUnits.Undefined), new UnitInfo(ElectricConductivityUnit.SiemensPerMeter, "SiemensPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricConductivity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -86,9 +82,6 @@ static ElectricConductivity() /// If value is NaN or Infinity. public ElectricConductivity(double value, ElectricConductivityUnit unit) { - if (unit == ElectricConductivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -132,24 +125,6 @@ public ElectricConductivity(double value, UnitSystem unitSystem) /// public static ElectricConductivityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricConductivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricConductivity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricConductivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricConductivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricConductivity quantity. /// @@ -169,6 +144,9 @@ public ElectricConductivity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -180,12 +158,6 @@ public ElectricConductivity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricConductivity; - /// /// The of this quantity. /// @@ -278,7 +250,7 @@ public static string GetAbbreviation(ElectricConductivityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricConductivityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -412,7 +384,7 @@ public static ElectricConductivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricConductivity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -443,7 +415,7 @@ public static bool TryParse(string? str, out ElectricConductivity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricConductivity result) { return QuantityParser.Default.TryParse( @@ -471,7 +443,7 @@ public static ElectricConductivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -497,7 +469,7 @@ public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricConductivityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -577,20 +549,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricConductivity left, ElectricConductivity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricConductivity left, ElectricConductivity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -606,23 +564,6 @@ public int CompareTo(ElectricConductivity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricConductivity objElectricConductivity)) - return false; - - return Equals(objElectricConductivity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricConductivity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricConductivity within the given absolute or relative tolerance. @@ -668,7 +609,7 @@ public bool Equals(ElectricConductivity other, double tolerance, ComparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -694,10 +635,9 @@ public override int GetHashCode() public double As(ElectricConductivityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -718,10 +658,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricConductivityUnit unitAsElectricConductivityUnit)) + if (!(unit is ElectricConductivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricConductivityUnit); + return (double)As(typedUnit); } /// @@ -804,10 +744,10 @@ private bool TryToUnit(ElectricConductivityUnit unit, out ElectricConductivity? /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricConductivityUnit unitAsElectricConductivityUnit)) + 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(unitAsElectricConductivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -851,63 +791,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -989,8 +895,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricConductivityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricConductivity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricConductivity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index a1ee5dd8fa..4b135166bf 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma. /// [DataContract] - public readonly partial struct ElectricCurrent : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricCurrent : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricCurrent() { BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); BaseUnit = ElectricCurrentUnit.Ampere; - MaxValue = new ElectricCurrent(double.MaxValue, BaseUnit); - MinValue = new ElectricCurrent(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCurrent; - Units = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().Except(new ElectricCurrentUnit[]{ ElectricCurrentUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().ToArray(); Zero = new ElectricCurrent(0, BaseUnit); Info = new QuantityInfo("ElectricCurrent", new UnitInfo[] @@ -71,7 +67,7 @@ static ElectricCurrent() new UnitInfo(ElectricCurrentUnit.Nanoampere, "Nanoamperes", BaseUnits.Undefined), new UnitInfo(ElectricCurrentUnit.Picoampere, "Picoamperes", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCurrent); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -85,9 +81,6 @@ static ElectricCurrent() /// If value is NaN or Infinity. public ElectricCurrent(double value, ElectricCurrentUnit unit) { - if (unit == ElectricCurrentUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -131,24 +124,6 @@ public ElectricCurrent(double value, UnitSystem unitSystem) /// public static ElectricCurrentUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricCurrent - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCurrent MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCurrent - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCurrent MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricCurrent quantity. /// @@ -168,6 +143,9 @@ public ElectricCurrent(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -179,12 +157,6 @@ public ElectricCurrent(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricCurrent; - /// /// The of this quantity. /// @@ -293,7 +265,7 @@ public static string GetAbbreviation(ElectricCurrentUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricCurrentUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -447,7 +419,7 @@ public static ElectricCurrent Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCurrent Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -478,7 +450,7 @@ public static bool TryParse(string? str, out ElectricCurrent result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCurrent result) { return QuantityParser.Default.TryParse( @@ -506,7 +478,7 @@ public static ElectricCurrentUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -532,7 +504,7 @@ public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricCurrentUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -612,20 +584,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricCurrent left, ElectricCurrent right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricCurrent left, ElectricCurrent right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -641,23 +599,6 @@ public int CompareTo(ElectricCurrent other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCurrent objElectricCurrent)) - return false; - - return Equals(objElectricCurrent); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricCurrent other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricCurrent within the given absolute or relative tolerance. @@ -703,7 +644,7 @@ public bool Equals(ElectricCurrent other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -729,10 +670,9 @@ public override int GetHashCode() public double As(ElectricCurrentUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -753,10 +693,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricCurrentUnit unitAsElectricCurrentUnit)) + if (!(unit is ElectricCurrentUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); - return As(unitAsElectricCurrentUnit); + return (double)As(typedUnit); } /// @@ -843,10 +783,10 @@ private bool TryToUnit(ElectricCurrentUnit unit, out ElectricCurrent? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricCurrentUnit unitAsElectricCurrentUnit)) + 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(unitAsElectricCurrentUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -890,63 +830,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1028,8 +934,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricCurrentUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricCurrent.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricCurrent.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index f9dc62de72..079f822f5e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Current_density /// [DataContract] - public readonly partial struct ElectricCurrentDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricCurrentDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricCurrentDensity() { BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); BaseUnit = ElectricCurrentDensityUnit.AmperePerSquareMeter; - MaxValue = new ElectricCurrentDensity(double.MaxValue, BaseUnit); - MinValue = new ElectricCurrentDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCurrentDensity; - Units = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().Except(new ElectricCurrentDensityUnit[]{ ElectricCurrentDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().ToArray(); Zero = new ElectricCurrentDensity(0, BaseUnit); Info = new QuantityInfo("ElectricCurrentDensity", new UnitInfo[] @@ -69,7 +65,7 @@ static ElectricCurrentDensity() new UnitInfo(ElectricCurrentDensityUnit.AmperePerSquareInch, "AmperesPerSquareInch", new BaseUnits(length: LengthUnit.Inch, current: ElectricCurrentUnit.Ampere)), new UnitInfo(ElectricCurrentDensityUnit.AmperePerSquareMeter, "AmperesPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCurrentDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static ElectricCurrentDensity() /// If value is NaN or Infinity. public ElectricCurrentDensity(double value, ElectricCurrentDensityUnit unit) { - if (unit == ElectricCurrentDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) /// public static ElectricCurrentDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricCurrentDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCurrentDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCurrentDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCurrentDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricCurrentDensity quantity. /// @@ -166,6 +141,9 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricCurrentDensity; - /// /// The of this quantity. /// @@ -251,7 +223,7 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricCurrentDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -355,7 +327,7 @@ public static ElectricCurrentDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCurrentDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -386,7 +358,7 @@ public static bool TryParse(string? str, out ElectricCurrentDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCurrentDensity result) { return QuantityParser.Default.TryParse( @@ -414,7 +386,7 @@ public static ElectricCurrentDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -440,7 +412,7 @@ public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricCurrentDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -520,20 +492,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -549,23 +507,6 @@ public int CompareTo(ElectricCurrentDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCurrentDensity objElectricCurrentDensity)) - return false; - - return Equals(objElectricCurrentDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricCurrentDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricCurrentDensity within the given absolute or relative tolerance. @@ -611,7 +552,7 @@ public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonTyp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -637,10 +578,9 @@ public override int GetHashCode() public double As(ElectricCurrentDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -661,10 +601,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricCurrentDensityUnit unitAsElectricCurrentDensityUnit)) + if (!(unit is ElectricCurrentDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricCurrentDensityUnit); + return (double)As(typedUnit); } /// @@ -741,10 +681,10 @@ private bool TryToUnit(ElectricCurrentDensityUnit unit, out ElectricCurrentDensi /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricCurrentDensityUnit unitAsElectricCurrentDensityUnit)) + 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(unitAsElectricCurrentDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -788,63 +728,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -926,8 +832,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricCurrentDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricCurrentDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricCurrentDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index 4b8b7bd9ec..419eb6f735 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In electromagnetism, the current gradient describes how the current changes in time. /// [DataContract] - public readonly partial struct ElectricCurrentGradient : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricCurrentGradient : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricCurrentGradient() { BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); BaseUnit = ElectricCurrentGradientUnit.AmperePerSecond; - MaxValue = new ElectricCurrentGradient(double.MaxValue, BaseUnit); - MinValue = new ElectricCurrentGradient(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricCurrentGradient; - Units = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().Except(new ElectricCurrentGradientUnit[]{ ElectricCurrentGradientUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().ToArray(); Zero = new ElectricCurrentGradient(0, BaseUnit); Info = new QuantityInfo("ElectricCurrentGradient", new UnitInfo[] @@ -67,7 +63,7 @@ static ElectricCurrentGradient() new UnitInfo(ElectricCurrentGradientUnit.AmperePerNanosecond, "AmperesPerNanosecond", new BaseUnits(time: DurationUnit.Nanosecond, current: ElectricCurrentUnit.Ampere)), new UnitInfo(ElectricCurrentGradientUnit.AmperePerSecond, "AmperesPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricCurrentGradient); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static ElectricCurrentGradient() /// If value is NaN or Infinity. public ElectricCurrentGradient(double value, ElectricCurrentGradientUnit unit) { - if (unit == ElectricCurrentGradientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) /// public static ElectricCurrentGradientUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricCurrentGradient - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCurrentGradient MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricCurrentGradient - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricCurrentGradient MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricCurrentGradient quantity. /// @@ -164,6 +139,9 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricCurrentGradient; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricCurrentGradientUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static ElectricCurrentGradient Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCurrentGradient Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out ElectricCurrentGradient result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCurrentGradient result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static ElectricCurrentGradientUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricCurrentGradientUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -536,20 +508,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -565,23 +523,6 @@ public int CompareTo(ElectricCurrentGradient other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricCurrentGradient objElectricCurrentGradient)) - return false; - - return Equals(objElectricCurrentGradient); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricCurrentGradient other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricCurrentGradient within the given absolute or relative tolerance. @@ -627,7 +568,7 @@ public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -653,10 +594,9 @@ public override int GetHashCode() public double As(ElectricCurrentGradientUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -677,10 +617,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricCurrentGradientUnit unitAsElectricCurrentGradientUnit)) + if (!(unit is ElectricCurrentGradientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); - return As(unitAsElectricCurrentGradientUnit); + return (double)As(typedUnit); } /// @@ -759,10 +699,10 @@ private bool TryToUnit(ElectricCurrentGradientUnit unit, out ElectricCurrentGrad /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricCurrentGradientUnit unitAsElectricCurrentGradientUnit)) + 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(unitAsElectricCurrentGradientUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -806,63 +746,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -944,8 +850,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricCurrentGradientUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricCurrentGradient.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricCurrentGradient.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index 9631d9cf98..7c51cf0ec9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electric_field /// [DataContract] - public readonly partial struct ElectricField : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricField : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static ElectricField() { BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); BaseUnit = ElectricFieldUnit.VoltPerMeter; - MaxValue = new ElectricField(double.MaxValue, BaseUnit); - MinValue = new ElectricField(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricField; - Units = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().Except(new ElectricFieldUnit[]{ ElectricFieldUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().ToArray(); Zero = new ElectricField(0, BaseUnit); Info = new QuantityInfo("ElectricField", new UnitInfo[] { new UnitInfo(ElectricFieldUnit.VoltPerMeter, "VoltsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricField); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static ElectricField() /// If value is NaN or Infinity. public ElectricField(double value, ElectricFieldUnit unit) { - if (unit == ElectricFieldUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public ElectricField(double value, UnitSystem unitSystem) /// public static ElectricFieldUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricField - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricField MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricField - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricField MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricField quantity. /// @@ -164,6 +139,9 @@ public ElectricField(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public ElectricField(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricField; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(ElectricFieldUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricFieldUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static ElectricField Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricField Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out ElectricField result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricField result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static ElectricFieldUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out ElectricFieldUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricFieldUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricField left, ElectricField right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricField left, ElectricField right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(ElectricField other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricField objElectricField)) - return false; - - return Equals(objElectricField); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricField other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricField within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(ElectricField other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(ElectricFieldUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricFieldUnit unitAsElectricFieldUnit)) + if (!(unit is ElectricFieldUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); - return As(unitAsElectricFieldUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(ElectricFieldUnit unit, out ElectricField? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricFieldUnit unitAsElectricFieldUnit)) + 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(unitAsElectricFieldUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricFieldUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricField.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricField.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index 42510de597..9b760aff32 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Inductance /// [DataContract] - public readonly partial struct ElectricInductance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricInductance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricInductance() { BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); BaseUnit = ElectricInductanceUnit.Henry; - MaxValue = new ElectricInductance(double.MaxValue, BaseUnit); - MinValue = new ElectricInductance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricInductance; - Units = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().Except(new ElectricInductanceUnit[]{ ElectricInductanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().ToArray(); Zero = new ElectricInductance(0, BaseUnit); Info = new QuantityInfo("ElectricInductance", new UnitInfo[] @@ -70,7 +66,7 @@ static ElectricInductance() new UnitInfo(ElectricInductanceUnit.Millihenry, "Millihenries", BaseUnits.Undefined), new UnitInfo(ElectricInductanceUnit.Nanohenry, "Nanohenries", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricInductance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static ElectricInductance() /// If value is NaN or Infinity. public ElectricInductance(double value, ElectricInductanceUnit unit) { - if (unit == ElectricInductanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public ElectricInductance(double value, UnitSystem unitSystem) /// public static ElectricInductanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricInductance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricInductance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricInductance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricInductance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricInductance quantity. /// @@ -167,6 +142,9 @@ public ElectricInductance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public ElectricInductance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricInductance; - /// /// The of this quantity. /// @@ -260,7 +232,7 @@ public static string GetAbbreviation(ElectricInductanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricInductanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -374,7 +346,7 @@ public static ElectricInductance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricInductance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -405,7 +377,7 @@ public static bool TryParse(string? str, out ElectricInductance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricInductance result) { return QuantityParser.Default.TryParse( @@ -433,7 +405,7 @@ public static ElectricInductanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -459,7 +431,7 @@ public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricInductanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -539,20 +511,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricInductance left, ElectricInductance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricInductance left, ElectricInductance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -568,23 +526,6 @@ public int CompareTo(ElectricInductance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricInductance objElectricInductance)) - return false; - - return Equals(objElectricInductance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricInductance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricInductance within the given absolute or relative tolerance. @@ -630,7 +571,7 @@ public bool Equals(ElectricInductance other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -656,10 +597,9 @@ public override int GetHashCode() public double As(ElectricInductanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -680,10 +620,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricInductanceUnit unitAsElectricInductanceUnit)) + if (!(unit is ElectricInductanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricInductanceUnit); + return (double)As(typedUnit); } /// @@ -762,10 +702,10 @@ private bool TryToUnit(ElectricInductanceUnit unit, out ElectricInductance? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricInductanceUnit unitAsElectricInductanceUnit)) + 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(unitAsElectricInductanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -809,63 +749,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -947,8 +853,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricInductanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricInductance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricInductance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index 388fb2e200..70cf5a6f67 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point. /// [DataContract] - public readonly partial struct ElectricPotential : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricPotential : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricPotential() { BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); BaseUnit = ElectricPotentialUnit.Volt; - MaxValue = new ElectricPotential(double.MaxValue, BaseUnit); - MinValue = new ElectricPotential(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotential; - Units = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().Except(new ElectricPotentialUnit[]{ ElectricPotentialUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().ToArray(); Zero = new ElectricPotential(0, BaseUnit); Info = new QuantityInfo("ElectricPotential", new UnitInfo[] @@ -68,7 +64,7 @@ static ElectricPotential() new UnitInfo(ElectricPotentialUnit.Millivolt, "Millivolts", BaseUnits.Undefined), new UnitInfo(ElectricPotentialUnit.Volt, "Volts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotential); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -82,9 +78,6 @@ static ElectricPotential() /// If value is NaN or Infinity. public ElectricPotential(double value, ElectricPotentialUnit unit) { - if (unit == ElectricPotentialUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -128,24 +121,6 @@ public ElectricPotential(double value, UnitSystem unitSystem) /// public static ElectricPotentialUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricPotential - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotential MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotential - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotential MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricPotential quantity. /// @@ -165,6 +140,9 @@ public ElectricPotential(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -176,12 +154,6 @@ public ElectricPotential(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricPotential; - /// /// The of this quantity. /// @@ -271,7 +243,7 @@ public static string GetAbbreviation(ElectricPotentialUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricPotentialUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -395,7 +367,7 @@ public static ElectricPotential Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricPotential Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -426,7 +398,7 @@ public static bool TryParse(string? str, out ElectricPotential result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotential result) { return QuantityParser.Default.TryParse( @@ -454,7 +426,7 @@ public static ElectricPotentialUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -480,7 +452,7 @@ public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -560,20 +532,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricPotential left, ElectricPotential right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricPotential left, ElectricPotential right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -589,23 +547,6 @@ public int CompareTo(ElectricPotential other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotential objElectricPotential)) - return false; - - return Equals(objElectricPotential); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricPotential other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricPotential within the given absolute or relative tolerance. @@ -651,7 +592,7 @@ public bool Equals(ElectricPotential other, double tolerance, ComparisonType com if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -677,10 +618,9 @@ public override int GetHashCode() public double As(ElectricPotentialUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -701,10 +641,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialUnit unitAsElectricPotentialUnit)) + if (!(unit is ElectricPotentialUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialUnit); + return (double)As(typedUnit); } /// @@ -785,10 +725,10 @@ private bool TryToUnit(ElectricPotentialUnit unit, out ElectricPotential? conver /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialUnit unitAsElectricPotentialUnit)) + 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(unitAsElectricPotentialUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -832,63 +772,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -970,8 +876,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricPotentialUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricPotential.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricPotential.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs index 12e18ded62..0e901edbf6 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The Electric Potential of a system known to use Alternating Current. /// [DataContract] - public readonly partial struct ElectricPotentialAc : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricPotentialAc : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricPotentialAc() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = ElectricPotentialAcUnit.VoltAc; - MaxValue = new ElectricPotentialAc(double.MaxValue, BaseUnit); - MinValue = new ElectricPotentialAc(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotentialAc; - Units = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().ToArray(); Zero = new ElectricPotentialAc(0, BaseUnit); Info = new QuantityInfo("ElectricPotentialAc", new UnitInfo[] @@ -68,7 +64,7 @@ static ElectricPotentialAc() new UnitInfo(ElectricPotentialAcUnit.MillivoltAc, "MillivoltsAc", BaseUnits.Undefined), new UnitInfo(ElectricPotentialAcUnit.VoltAc, "VoltsAc", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotentialAc); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -82,9 +78,6 @@ static ElectricPotentialAc() /// If value is NaN or Infinity. public ElectricPotentialAc(double value, ElectricPotentialAcUnit unit) { - if (unit == ElectricPotentialAcUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -128,24 +121,6 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) /// public static ElectricPotentialAcUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricPotentialAc - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotentialAc MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotentialAc - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotentialAc MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricPotentialAc quantity. /// @@ -165,6 +140,9 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -176,12 +154,6 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricPotentialAc; - /// /// The of this quantity. /// @@ -266,7 +238,7 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricPotentialAcUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -390,7 +362,7 @@ public static ElectricPotentialAc Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricPotentialAc Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -421,7 +393,7 @@ public static bool TryParse(string? str, out ElectricPotentialAc result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotentialAc result) { return QuantityParser.Default.TryParse( @@ -449,7 +421,7 @@ public static ElectricPotentialAcUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -475,7 +447,7 @@ public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialAcUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -555,20 +527,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -584,23 +542,6 @@ public int CompareTo(ElectricPotentialAc other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotentialAc objElectricPotentialAc)) - return false; - - return Equals(objElectricPotentialAc); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricPotentialAc other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricPotentialAc within the given absolute or relative tolerance. @@ -646,7 +587,7 @@ public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -672,10 +613,9 @@ public override int GetHashCode() public double As(ElectricPotentialAcUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -696,10 +636,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit)) + if (!(unit is ElectricPotentialAcUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialAcUnit); + return (double)As(typedUnit); } /// @@ -780,10 +720,10 @@ private bool TryToUnit(ElectricPotentialAcUnit unit, out ElectricPotentialAc? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit)) + 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(unitAsElectricPotentialAcUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -827,63 +767,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -965,8 +871,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricPotentialAcUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricPotentialAc.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricPotentialAc.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index 58f95e0937..2d903a3775 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// 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). /// [DataContract] - public readonly partial struct ElectricPotentialChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricPotentialChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricPotentialChangeRate() { BaseDimensions = new BaseDimensions(2, 1, -4, -1, 0, 0, 0); BaseUnit = ElectricPotentialChangeRateUnit.VoltPerSecond; - MaxValue = new ElectricPotentialChangeRate(double.MaxValue, BaseUnit); - MinValue = new ElectricPotentialChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotentialChangeRate; - Units = Enum.GetValues(typeof(ElectricPotentialChangeRateUnit)).Cast().Except(new ElectricPotentialChangeRateUnit[]{ ElectricPotentialChangeRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricPotentialChangeRateUnit)).Cast().ToArray(); Zero = new ElectricPotentialChangeRate(0, BaseUnit); Info = new QuantityInfo("ElectricPotentialChangeRate", new UnitInfo[] @@ -83,7 +79,7 @@ static ElectricPotentialChangeRate() new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerMinute, "VoltsPerMinutes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere)), new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerSecond, "VoltsPerSeconds", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotentialChangeRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -97,9 +93,6 @@ static ElectricPotentialChangeRate() /// If value is NaN or Infinity. public ElectricPotentialChangeRate(double value, ElectricPotentialChangeRateUnit unit) { - if (unit == ElectricPotentialChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -143,24 +136,6 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) /// public static ElectricPotentialChangeRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricPotentialChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotentialChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotentialChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotentialChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricPotentialChangeRate quantity. /// @@ -180,6 +155,9 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -191,12 +169,6 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricPotentialChangeRate; - /// /// The of this quantity. /// @@ -401,7 +373,7 @@ public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -675,7 +647,7 @@ public static ElectricPotentialChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricPotentialChangeRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -706,7 +678,7 @@ public static bool TryParse(string? str, out ElectricPotentialChangeRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotentialChangeRate result) { return QuantityParser.Default.TryParse( @@ -734,7 +706,7 @@ public static ElectricPotentialChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -760,7 +732,7 @@ public static bool TryParseUnit(string str, out ElectricPotentialChangeRateUnit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialChangeRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -840,20 +812,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -869,23 +827,6 @@ public int CompareTo(ElectricPotentialChangeRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotentialChangeRate objElectricPotentialChangeRate)) - return false; - - return Equals(objElectricPotentialChangeRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricPotentialChangeRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricPotentialChangeRate within the given absolute or relative tolerance. @@ -931,7 +872,7 @@ public bool Equals(ElectricPotentialChangeRate other, double tolerance, Comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -957,10 +898,9 @@ public override int GetHashCode() public double As(ElectricPotentialChangeRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -981,10 +921,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialChangeRateUnit unitAsElectricPotentialChangeRateUnit)) + if (!(unit is ElectricPotentialChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialChangeRateUnit); + return (double)As(typedUnit); } /// @@ -1095,10 +1035,10 @@ private bool TryToUnit(ElectricPotentialChangeRateUnit unit, out ElectricPotenti /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialChangeRateUnit unitAsElectricPotentialChangeRateUnit)) + 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(unitAsElectricPotentialChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1142,63 +1082,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1280,8 +1186,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricPotentialChangeRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricPotentialChangeRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricPotentialChangeRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs index 47e7ac2e8b..6234835396 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The Electric Potential of a system known to use Direct Current. /// [DataContract] - public readonly partial struct ElectricPotentialDc : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricPotentialDc : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricPotentialDc() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = ElectricPotentialDcUnit.VoltDc; - MaxValue = new ElectricPotentialDc(double.MaxValue, BaseUnit); - MinValue = new ElectricPotentialDc(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricPotentialDc; - Units = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().Except(new ElectricPotentialDcUnit[]{ ElectricPotentialDcUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().ToArray(); Zero = new ElectricPotentialDc(0, BaseUnit); Info = new QuantityInfo("ElectricPotentialDc", new UnitInfo[] @@ -68,7 +64,7 @@ static ElectricPotentialDc() new UnitInfo(ElectricPotentialDcUnit.MillivoltDc, "MillivoltsDc", BaseUnits.Undefined), new UnitInfo(ElectricPotentialDcUnit.VoltDc, "VoltsDc", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricPotentialDc); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -82,9 +78,6 @@ static ElectricPotentialDc() /// If value is NaN or Infinity. public ElectricPotentialDc(double value, ElectricPotentialDcUnit unit) { - if (unit == ElectricPotentialDcUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -128,24 +121,6 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) /// public static ElectricPotentialDcUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricPotentialDc - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotentialDc MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricPotentialDc - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricPotentialDc MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricPotentialDc quantity. /// @@ -165,6 +140,9 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -176,12 +154,6 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricPotentialDc; - /// /// The of this quantity. /// @@ -266,7 +238,7 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricPotentialDcUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -390,7 +362,7 @@ public static ElectricPotentialDc Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricPotentialDc Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -421,7 +393,7 @@ public static bool TryParse(string? str, out ElectricPotentialDc result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotentialDc result) { return QuantityParser.Default.TryParse( @@ -449,7 +421,7 @@ public static ElectricPotentialDcUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -475,7 +447,7 @@ public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialDcUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -555,20 +527,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricPotentialDc left, ElectricPotentialDc right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricPotentialDc left, ElectricPotentialDc right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -584,23 +542,6 @@ public int CompareTo(ElectricPotentialDc other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricPotentialDc objElectricPotentialDc)) - return false; - - return Equals(objElectricPotentialDc); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricPotentialDc other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricPotentialDc within the given absolute or relative tolerance. @@ -646,7 +587,7 @@ public bool Equals(ElectricPotentialDc other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -672,10 +613,9 @@ public override int GetHashCode() public double As(ElectricPotentialDcUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -696,10 +636,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricPotentialDcUnit unitAsElectricPotentialDcUnit)) + if (!(unit is ElectricPotentialDcUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); - return As(unitAsElectricPotentialDcUnit); + return (double)As(typedUnit); } /// @@ -780,10 +720,10 @@ private bool TryToUnit(ElectricPotentialDcUnit unit, out ElectricPotentialDc? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricPotentialDcUnit unitAsElectricPotentialDcUnit)) + 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(unitAsElectricPotentialDcUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -827,63 +767,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -965,8 +871,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricPotentialDcUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricPotentialDc.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricPotentialDc.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 63f738bf3b..15cf46a18b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. /// [DataContract] - public readonly partial struct ElectricResistance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricResistance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ElectricResistance() { BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); BaseUnit = ElectricResistanceUnit.Ohm; - MaxValue = new ElectricResistance(double.MaxValue, BaseUnit); - MinValue = new ElectricResistance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricResistance; - Units = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().Except(new ElectricResistanceUnit[]{ ElectricResistanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().ToArray(); Zero = new ElectricResistance(0, BaseUnit); Info = new QuantityInfo("ElectricResistance", new UnitInfo[] @@ -69,7 +65,7 @@ static ElectricResistance() new UnitInfo(ElectricResistanceUnit.Milliohm, "Milliohms", BaseUnits.Undefined), new UnitInfo(ElectricResistanceUnit.Ohm, "Ohms", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricResistance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static ElectricResistance() /// If value is NaN or Infinity. public ElectricResistance(double value, ElectricResistanceUnit unit) { - if (unit == ElectricResistanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public ElectricResistance(double value, UnitSystem unitSystem) /// public static ElectricResistanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricResistance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricResistance MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricResistance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricResistance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricResistance quantity. /// @@ -166,6 +141,9 @@ public ElectricResistance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public ElectricResistance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricResistance; - /// /// The of this quantity. /// @@ -275,7 +247,7 @@ public static string GetAbbreviation(ElectricResistanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricResistanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -409,7 +381,7 @@ public static ElectricResistance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricResistance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -440,7 +412,7 @@ public static bool TryParse(string? str, out ElectricResistance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricResistance result) { return QuantityParser.Default.TryParse( @@ -468,7 +440,7 @@ public static ElectricResistanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -494,7 +466,7 @@ public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricResistanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -574,20 +546,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricResistance left, ElectricResistance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricResistance left, ElectricResistance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -603,23 +561,6 @@ public int CompareTo(ElectricResistance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricResistance objElectricResistance)) - return false; - - return Equals(objElectricResistance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricResistance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricResistance within the given absolute or relative tolerance. @@ -665,7 +606,7 @@ public bool Equals(ElectricResistance other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -691,10 +632,9 @@ public override int GetHashCode() public double As(ElectricResistanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -715,10 +655,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit)) + if (!(unit is ElectricResistanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); - return As(unitAsElectricResistanceUnit); + return (double)As(typedUnit); } /// @@ -801,10 +741,10 @@ private bool TryToUnit(ElectricResistanceUnit unit, out ElectricResistance? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricResistanceUnit unitAsElectricResistanceUnit)) + 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(unitAsElectricResistanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -848,63 +788,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -986,8 +892,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricResistanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricResistance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricResistance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index 9bbc360b6d..b3857f6e0b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity /// [DataContract] - public readonly partial struct ElectricResistivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricResistivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricResistivity() { BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); BaseUnit = ElectricResistivityUnit.OhmMeter; - MaxValue = new ElectricResistivity(double.MaxValue, BaseUnit); - MinValue = new ElectricResistivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricResistivity; - Units = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().Except(new ElectricResistivityUnit[]{ ElectricResistivityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().ToArray(); Zero = new ElectricResistivity(0, BaseUnit); Info = new QuantityInfo("ElectricResistivity", new UnitInfo[] @@ -80,7 +76,7 @@ static ElectricResistivity() new UnitInfo(ElectricResistivityUnit.PicoohmCentimeter, "PicoohmsCentimeter", BaseUnits.Undefined), new UnitInfo(ElectricResistivityUnit.PicoohmMeter, "PicoohmMeters", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricResistivity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -94,9 +90,6 @@ static ElectricResistivity() /// If value is NaN or Infinity. public ElectricResistivity(double value, ElectricResistivityUnit unit) { - if (unit == ElectricResistivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -140,24 +133,6 @@ public ElectricResistivity(double value, UnitSystem unitSystem) /// public static ElectricResistivityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricResistivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricResistivity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricResistivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricResistivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricResistivity quantity. /// @@ -177,6 +152,9 @@ public ElectricResistivity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -188,12 +166,6 @@ public ElectricResistivity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricResistivity; - /// /// The of this quantity. /// @@ -350,7 +322,7 @@ public static string GetAbbreviation(ElectricResistivityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricResistivityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -564,7 +536,7 @@ public static ElectricResistivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricResistivity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -595,7 +567,7 @@ public static bool TryParse(string? str, out ElectricResistivity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricResistivity result) { return QuantityParser.Default.TryParse( @@ -623,7 +595,7 @@ public static ElectricResistivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -649,7 +621,7 @@ public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricResistivityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -729,20 +701,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricResistivity left, ElectricResistivity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricResistivity left, ElectricResistivity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -758,23 +716,6 @@ public int CompareTo(ElectricResistivity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricResistivity objElectricResistivity)) - return false; - - return Equals(objElectricResistivity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricResistivity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricResistivity within the given absolute or relative tolerance. @@ -820,7 +761,7 @@ public bool Equals(ElectricResistivity other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -846,10 +787,9 @@ public override int GetHashCode() public double As(ElectricResistivityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -870,10 +810,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricResistivityUnit unitAsElectricResistivityUnit)) + if (!(unit is ElectricResistivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricResistivityUnit); + return (double)As(typedUnit); } /// @@ -972,10 +912,10 @@ private bool TryToUnit(ElectricResistivityUnit unit, out ElectricResistivity? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricResistivityUnit unitAsElectricResistivityUnit)) + 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(unitAsElectricResistivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1019,63 +959,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1157,8 +1063,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricResistivityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricResistivity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricResistivity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index 3016e7f656..c795aaedc2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Charge_density /// [DataContract] - public readonly partial struct ElectricSurfaceChargeDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ElectricSurfaceChargeDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ElectricSurfaceChargeDensity() { BaseDimensions = new BaseDimensions(-2, 0, 1, 1, 0, 0, 0); BaseUnit = ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter; - MaxValue = new ElectricSurfaceChargeDensity(double.MaxValue, BaseUnit); - MinValue = new ElectricSurfaceChargeDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ElectricSurfaceChargeDensity; - Units = Enum.GetValues(typeof(ElectricSurfaceChargeDensityUnit)).Cast().Except(new ElectricSurfaceChargeDensityUnit[]{ ElectricSurfaceChargeDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ElectricSurfaceChargeDensityUnit)).Cast().ToArray(); Zero = new ElectricSurfaceChargeDensity(0, BaseUnit); Info = new QuantityInfo("ElectricSurfaceChargeDensity", new UnitInfo[] @@ -69,7 +65,7 @@ static ElectricSurfaceChargeDensity() new UnitInfo(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, "CoulombsPerSquareInch", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), new UnitInfo(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, "CoulombsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ElectricSurfaceChargeDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static ElectricSurfaceChargeDensity() /// If value is NaN or Infinity. public ElectricSurfaceChargeDensity(double value, ElectricSurfaceChargeDensityUnit unit) { - if (unit == ElectricSurfaceChargeDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) /// public static ElectricSurfaceChargeDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ElectricSurfaceChargeDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricSurfaceChargeDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of ElectricSurfaceChargeDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ElectricSurfaceChargeDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ElectricSurfaceChargeDensity quantity. /// @@ -166,6 +141,9 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ElectricSurfaceChargeDensity; - /// /// The of this quantity. /// @@ -251,7 +223,7 @@ public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -355,7 +327,7 @@ public static ElectricSurfaceChargeDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ElectricSurfaceChargeDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -386,7 +358,7 @@ public static bool TryParse(string? str, out ElectricSurfaceChargeDensity result /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ElectricSurfaceChargeDensity result) { return QuantityParser.Default.TryParse( @@ -414,7 +386,7 @@ public static ElectricSurfaceChargeDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -440,7 +412,7 @@ public static bool TryParseUnit(string str, out ElectricSurfaceChargeDensityUnit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricSurfaceChargeDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -520,20 +492,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Elect return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -549,23 +507,6 @@ public int CompareTo(ElectricSurfaceChargeDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ElectricSurfaceChargeDensity objElectricSurfaceChargeDensity)) - return false; - - return Equals(objElectricSurfaceChargeDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ElectricSurfaceChargeDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ElectricSurfaceChargeDensity within the given absolute or relative tolerance. @@ -611,7 +552,7 @@ public bool Equals(ElectricSurfaceChargeDensity other, double tolerance, Compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -637,10 +578,9 @@ public override int GetHashCode() public double As(ElectricSurfaceChargeDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -661,10 +601,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ElectricSurfaceChargeDensityUnit unitAsElectricSurfaceChargeDensityUnit)) + if (!(unit is ElectricSurfaceChargeDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); - return As(unitAsElectricSurfaceChargeDensityUnit); + return (double)As(typedUnit); } /// @@ -741,10 +681,10 @@ private bool TryToUnit(ElectricSurfaceChargeDensityUnit unit, out ElectricSurfac /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ElectricSurfaceChargeDensityUnit unitAsElectricSurfaceChargeDensityUnit)) + 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(unitAsElectricSurfaceChargeDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -788,63 +728,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -926,8 +832,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ElectricSurfaceChargeDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ElectricSurfaceChargeDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ElectricSurfaceChargeDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index f8d63b02a4..cd54933b23 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used. /// [DataContract] - public readonly partial struct Energy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Energy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Energy() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); BaseUnit = EnergyUnit.Joule; - MaxValue = new Energy(double.MaxValue, BaseUnit); - MinValue = new Energy(double.MinValue, BaseUnit); - QuantityType = QuantityType.Energy; - Units = Enum.GetValues(typeof(EnergyUnit)).Cast().Except(new EnergyUnit[]{ EnergyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(EnergyUnit)).Cast().ToArray(); Zero = new Energy(0, BaseUnit); Info = new QuantityInfo("Energy", new UnitInfo[] @@ -101,7 +97,7 @@ static Energy() new UnitInfo(EnergyUnit.WattDay, "WattDays", BaseUnits.Undefined), new UnitInfo(EnergyUnit.WattHour, "WattHours", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Energy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -115,9 +111,6 @@ static Energy() /// If value is NaN or Infinity. public Energy(double value, EnergyUnit unit) { - if (unit == EnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -161,24 +154,6 @@ public Energy(double value, UnitSystem unitSystem) /// public static EnergyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Energy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Energy MaxValue { get; } - - /// - /// Represents the smallest possible value of Energy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Energy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Energy quantity. /// @@ -198,6 +173,9 @@ public Energy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -209,12 +187,6 @@ public Energy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Energy; - /// /// The of this quantity. /// @@ -584,7 +556,7 @@ public static string GetAbbreviation(EnergyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(EnergyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1038,7 +1010,7 @@ public static Energy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Energy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1069,7 +1041,7 @@ public static bool TryParse(string? str, out Energy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Energy result) { return QuantityParser.Default.TryParse( @@ -1097,7 +1069,7 @@ public static EnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1123,7 +1095,7 @@ public static bool TryParseUnit(string str, out EnergyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out EnergyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1203,20 +1175,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Energ return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Energy left, Energy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Energy left, Energy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1232,23 +1190,6 @@ public int CompareTo(Energy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Energy objEnergy)) - return false; - - return Equals(objEnergy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Energy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Energy within the given absolute or relative tolerance. @@ -1294,7 +1235,7 @@ public bool Equals(Energy other, double tolerance, ComparisonType comparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1320,10 +1261,9 @@ public override int GetHashCode() public double As(EnergyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1344,10 +1284,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is EnergyUnit unitAsEnergyUnit)) + if (!(unit is EnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); - return As(unitAsEnergyUnit); + return (double)As(typedUnit); } /// @@ -1494,10 +1434,10 @@ private bool TryToUnit(EnergyUnit unit, out Energy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is EnergyUnit unitAsEnergyUnit)) + 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(unitAsEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1541,63 +1481,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1679,8 +1585,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(EnergyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Energy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Energy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs index 59e546f7f3..0115f410d9 100644 --- a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,10 +32,10 @@ namespace UnitsNet { /// /// - /// Energy density is the amount of energy stored in a substance per unit volume and is measured in J/m³. It is sometimes confused with energy per unit mass which is properly called specific energy. + /// /// [DataContract] - public readonly partial struct EnergyDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct EnergyDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static EnergyDensity() { BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); BaseUnit = EnergyDensityUnit.JoulePerCubicMeter; - MaxValue = new EnergyDensity(double.MaxValue, BaseUnit); - MinValue = new EnergyDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.EnergyDensity; - Units = Enum.GetValues(typeof(EnergyDensityUnit)).Cast().Except(new EnergyDensityUnit[]{ EnergyDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(EnergyDensityUnit)).Cast().ToArray(); Zero = new EnergyDensity(0, BaseUnit); Info = new QuantityInfo("EnergyDensity", new UnitInfo[] @@ -75,7 +71,7 @@ static EnergyDensity() new UnitInfo(EnergyDensityUnit.TerawattHourPerCubicMeter, "TerawattHoursPerCubicMeter", BaseUnits.Undefined), new UnitInfo(EnergyDensityUnit.WattHourPerCubicMeter, "WattHoursPerCubicMeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.EnergyDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -89,9 +85,6 @@ static EnergyDensity() /// If value is NaN or Infinity. public EnergyDensity(double value, EnergyDensityUnit unit) { - if (unit == EnergyDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -135,24 +128,6 @@ public EnergyDensity(double value, UnitSystem unitSystem) /// public static EnergyDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of EnergyDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static EnergyDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of EnergyDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static EnergyDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the EnergyDensity quantity. /// @@ -172,6 +147,9 @@ public EnergyDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -183,12 +161,6 @@ public EnergyDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.EnergyDensity; - /// /// The of this quantity. /// @@ -329,7 +301,7 @@ public static string GetAbbreviation(EnergyDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(EnergyDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -523,7 +495,7 @@ public static EnergyDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static EnergyDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -554,7 +526,7 @@ public static bool TryParse(string? str, out EnergyDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out EnergyDensity result) { return QuantityParser.Default.TryParse( @@ -582,7 +554,7 @@ public static EnergyDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -608,7 +580,7 @@ public static bool TryParseUnit(string str, out EnergyDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out EnergyDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -688,20 +660,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Energ return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(EnergyDensity left, EnergyDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(EnergyDensity left, EnergyDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -717,23 +675,6 @@ public int CompareTo(EnergyDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is EnergyDensity objEnergyDensity)) - return false; - - return Equals(objEnergyDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(EnergyDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another EnergyDensity within the given absolute or relative tolerance. @@ -779,7 +720,7 @@ public bool Equals(EnergyDensity other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -805,10 +746,9 @@ public override int GetHashCode() public double As(EnergyDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -829,10 +769,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is EnergyDensityUnit unitAsEnergyDensityUnit)) + if (!(unit is EnergyDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyDensityUnit)} is supported.", nameof(unit)); - return As(unitAsEnergyDensityUnit); + return (double)As(typedUnit); } /// @@ -927,10 +867,10 @@ private bool TryToUnit(EnergyDensityUnit unit, out EnergyDensity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is EnergyDensityUnit unitAsEnergyDensityUnit)) + 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(unitAsEnergyDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -974,63 +914,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1112,8 +1018,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(EnergyDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return EnergyDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return EnergyDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index aaef9cc289..8d2bc12c8a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Entropy is an important concept in the branch of science known as thermodynamics. The idea of "irreversibility" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units /// [DataContract] - public readonly partial struct Entropy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Entropy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Entropy() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); BaseUnit = EntropyUnit.JoulePerKelvin; - MaxValue = new Entropy(double.MaxValue, BaseUnit); - MinValue = new Entropy(double.MinValue, BaseUnit); - QuantityType = QuantityType.Entropy; - Units = Enum.GetValues(typeof(EntropyUnit)).Cast().Except(new EntropyUnit[]{ EntropyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(EntropyUnit)).Cast().ToArray(); Zero = new Entropy(0, BaseUnit); Info = new QuantityInfo("Entropy", new UnitInfo[] @@ -70,7 +66,7 @@ static Entropy() new UnitInfo(EntropyUnit.KilojoulePerKelvin, "KilojoulesPerKelvin", BaseUnits.Undefined), new UnitInfo(EntropyUnit.MegajoulePerKelvin, "MegajoulesPerKelvin", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Entropy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static Entropy() /// If value is NaN or Infinity. public Entropy(double value, EntropyUnit unit) { - if (unit == EntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public Entropy(double value, UnitSystem unitSystem) /// public static EntropyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Entropy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Entropy MaxValue { get; } - - /// - /// Represents the smallest possible value of Entropy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Entropy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Entropy quantity. /// @@ -167,6 +142,9 @@ public Entropy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public Entropy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Entropy; - /// /// The of this quantity. /// @@ -284,7 +256,7 @@ public static string GetAbbreviation(EntropyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(EntropyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -428,7 +400,7 @@ public static Entropy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Entropy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -459,7 +431,7 @@ public static bool TryParse(string? str, out Entropy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Entropy result) { return QuantityParser.Default.TryParse( @@ -487,7 +459,7 @@ public static EntropyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -513,7 +485,7 @@ public static bool TryParseUnit(string str, out EntropyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out EntropyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -593,20 +565,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Entro return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Entropy left, Entropy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Entropy left, Entropy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -622,23 +580,6 @@ public int CompareTo(Entropy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Entropy objEntropy)) - return false; - - return Equals(objEntropy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Entropy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Entropy within the given absolute or relative tolerance. @@ -684,7 +625,7 @@ public bool Equals(Entropy other, double tolerance, ComparisonType comparisonTyp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -710,10 +651,9 @@ public override int GetHashCode() public double As(EntropyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -734,10 +674,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is EntropyUnit unitAsEntropyUnit)) + if (!(unit is EntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); - return As(unitAsEntropyUnit); + return (double)As(typedUnit); } /// @@ -822,10 +762,10 @@ private bool TryToUnit(EntropyUnit unit, out Entropy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is EntropyUnit unitAsEntropyUnit)) + 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(unitAsEntropyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -869,63 +809,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1007,8 +913,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(EntropyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Entropy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Entropy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index 0d01ea9dd3..73b60d4278 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F. /// [DataContract] - public readonly partial struct Force : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Force : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Force() { BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); BaseUnit = ForceUnit.Newton; - MaxValue = new Force(double.MaxValue, BaseUnit); - MinValue = new Force(double.MinValue, BaseUnit); - QuantityType = QuantityType.Force; - Units = Enum.GetValues(typeof(ForceUnit)).Cast().Except(new ForceUnit[]{ ForceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ForceUnit)).Cast().ToArray(); Zero = new Force(0, BaseUnit); Info = new QuantityInfo("Force", new UnitInfo[] @@ -78,7 +74,7 @@ static Force() new UnitInfo(ForceUnit.ShortTonForce, "ShortTonsForce", BaseUnits.Undefined), new UnitInfo(ForceUnit.TonneForce, "TonnesForce", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Force); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -92,9 +88,6 @@ static Force() /// If value is NaN or Infinity. public Force(double value, ForceUnit unit) { - if (unit == ForceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -138,24 +131,6 @@ public Force(double value, UnitSystem unitSystem) /// public static ForceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Force - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Force MaxValue { get; } - - /// - /// Represents the smallest possible value of Force - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Force MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Force quantity. /// @@ -175,6 +150,9 @@ public Force(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -186,12 +164,6 @@ public Force(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Force; - /// /// The of this quantity. /// @@ -369,7 +341,7 @@ public static string GetAbbreviation(ForceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ForceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -593,7 +565,7 @@ public static Force Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Force Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -624,7 +596,7 @@ public static bool TryParse(string? str, out Force result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Force result) { return QuantityParser.Default.TryParse( @@ -652,7 +624,7 @@ public static ForceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -678,7 +650,7 @@ public static bool TryParseUnit(string str, out ForceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ForceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -758,20 +730,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Force left, Force right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Force left, Force right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -787,23 +745,6 @@ public int CompareTo(Force other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Force objForce)) - return false; - - return Equals(objForce); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Force other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Force within the given absolute or relative tolerance. @@ -849,7 +790,7 @@ public bool Equals(Force other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -875,10 +816,9 @@ public override int GetHashCode() public double As(ForceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -899,10 +839,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ForceUnit unitAsForceUnit)) + if (!(unit is ForceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); - return As(unitAsForceUnit); + return (double)As(typedUnit); } /// @@ -1003,10 +943,10 @@ private bool TryToUnit(ForceUnit unit, out Force? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ForceUnit unitAsForceUnit)) + 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(unitAsForceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1050,63 +990,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1188,8 +1094,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ForceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Force.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Force.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index 96e330c6b5..80cbe233ce 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time). /// [DataContract] - public readonly partial struct ForceChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ForceChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ForceChangeRate() { BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); BaseUnit = ForceChangeRateUnit.NewtonPerSecond; - MaxValue = new ForceChangeRate(double.MaxValue, BaseUnit); - MinValue = new ForceChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.ForceChangeRate; - Units = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().Except(new ForceChangeRateUnit[]{ ForceChangeRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().ToArray(); Zero = new ForceChangeRate(0, BaseUnit); Info = new QuantityInfo("ForceChangeRate", new UnitInfo[] @@ -78,7 +74,7 @@ static ForceChangeRate() new UnitInfo(ForceChangeRateUnit.PoundForcePerMinute, "PoundsForcePerMinute", BaseUnits.Undefined), new UnitInfo(ForceChangeRateUnit.PoundForcePerSecond, "PoundsForcePerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ForceChangeRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -92,9 +88,6 @@ static ForceChangeRate() /// If value is NaN or Infinity. public ForceChangeRate(double value, ForceChangeRateUnit unit) { - if (unit == ForceChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -138,24 +131,6 @@ public ForceChangeRate(double value, UnitSystem unitSystem) /// public static ForceChangeRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ForceChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ForceChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of ForceChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ForceChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ForceChangeRate quantity. /// @@ -175,6 +150,9 @@ public ForceChangeRate(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -186,12 +164,6 @@ public ForceChangeRate(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ForceChangeRate; - /// /// The of this quantity. /// @@ -356,7 +328,7 @@ public static string GetAbbreviation(ForceChangeRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ForceChangeRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -580,7 +552,7 @@ public static ForceChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ForceChangeRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -611,7 +583,7 @@ public static bool TryParse(string? str, out ForceChangeRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ForceChangeRate result) { return QuantityParser.Default.TryParse( @@ -639,7 +611,7 @@ public static ForceChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -665,7 +637,7 @@ public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ForceChangeRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -745,20 +717,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ForceChangeRate left, ForceChangeRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ForceChangeRate left, ForceChangeRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -774,23 +732,6 @@ public int CompareTo(ForceChangeRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ForceChangeRate objForceChangeRate)) - return false; - - return Equals(objForceChangeRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ForceChangeRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ForceChangeRate within the given absolute or relative tolerance. @@ -836,7 +777,7 @@ public bool Equals(ForceChangeRate other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -862,10 +803,9 @@ public override int GetHashCode() public double As(ForceChangeRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -886,10 +826,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ForceChangeRateUnit unitAsForceChangeRateUnit)) + if (!(unit is ForceChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsForceChangeRateUnit); + return (double)As(typedUnit); } /// @@ -990,10 +930,10 @@ private bool TryToUnit(ForceChangeRateUnit unit, out ForceChangeRate? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ForceChangeRateUnit unitAsForceChangeRateUnit)) + 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(unitAsForceChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1037,63 +977,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1175,8 +1081,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ForceChangeRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ForceChangeRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ForceChangeRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index 2d0200cb67..894e7e2c8c 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The magnitude of force per unit length. /// [DataContract] - public readonly partial struct ForcePerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ForcePerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ForcePerLength() { BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); BaseUnit = ForcePerLengthUnit.NewtonPerMeter; - MaxValue = new ForcePerLength(double.MaxValue, BaseUnit); - MinValue = new ForcePerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.ForcePerLength; - Units = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().Except(new ForcePerLengthUnit[]{ ForcePerLengthUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().ToArray(); Zero = new ForcePerLength(0, BaseUnit); Info = new QuantityInfo("ForcePerLength", new UnitInfo[] @@ -101,7 +97,7 @@ static ForcePerLength() new UnitInfo(ForcePerLengthUnit.TonneForcePerMeter, "TonnesForcePerMeter", BaseUnits.Undefined), new UnitInfo(ForcePerLengthUnit.TonneForcePerMillimeter, "TonnesForcePerMillimeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ForcePerLength); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -115,9 +111,6 @@ static ForcePerLength() /// If value is NaN or Infinity. public ForcePerLength(double value, ForcePerLengthUnit unit) { - if (unit == ForcePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -161,24 +154,6 @@ public ForcePerLength(double value, UnitSystem unitSystem) /// public static ForcePerLengthUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ForcePerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ForcePerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of ForcePerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ForcePerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ForcePerLength quantity. /// @@ -198,6 +173,9 @@ public ForcePerLength(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -209,12 +187,6 @@ public ForcePerLength(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ForcePerLength; - /// /// The of this quantity. /// @@ -569,7 +541,7 @@ public static string GetAbbreviation(ForcePerLengthUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ForcePerLengthUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1023,7 +995,7 @@ public static ForcePerLength Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ForcePerLength Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1054,7 +1026,7 @@ public static bool TryParse(string? str, out ForcePerLength result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ForcePerLength result) { return QuantityParser.Default.TryParse( @@ -1082,7 +1054,7 @@ public static ForcePerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1108,7 +1080,7 @@ public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ForcePerLengthUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1188,20 +1160,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Force return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ForcePerLength left, ForcePerLength right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ForcePerLength left, ForcePerLength right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1217,23 +1175,6 @@ public int CompareTo(ForcePerLength other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ForcePerLength objForcePerLength)) - return false; - - return Equals(objForcePerLength); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ForcePerLength other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ForcePerLength within the given absolute or relative tolerance. @@ -1279,7 +1220,7 @@ public bool Equals(ForcePerLength other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1305,10 +1246,9 @@ public override int GetHashCode() public double As(ForcePerLengthUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1329,10 +1269,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ForcePerLengthUnit unitAsForcePerLengthUnit)) + if (!(unit is ForcePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsForcePerLengthUnit); + return (double)As(typedUnit); } /// @@ -1479,10 +1419,10 @@ private bool TryToUnit(ForcePerLengthUnit unit, out ForcePerLength? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ForcePerLengthUnit unitAsForcePerLengthUnit)) + 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(unitAsForcePerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1526,63 +1466,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1664,8 +1570,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ForcePerLengthUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ForcePerLength.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ForcePerLength.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index 24fca08e16..9320b73229 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The number of occurrences of a repeating event per unit time. /// [DataContract] - public readonly partial struct Frequency : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Frequency : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Frequency() { BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); BaseUnit = FrequencyUnit.Hertz; - MaxValue = new Frequency(double.MaxValue, BaseUnit); - MinValue = new Frequency(double.MinValue, BaseUnit); - QuantityType = QuantityType.Frequency; - Units = Enum.GetValues(typeof(FrequencyUnit)).Cast().Except(new FrequencyUnit[]{ FrequencyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(FrequencyUnit)).Cast().ToArray(); Zero = new Frequency(0, BaseUnit); Info = new QuantityInfo("Frequency", new UnitInfo[] @@ -74,7 +70,7 @@ static Frequency() new UnitInfo(FrequencyUnit.RadianPerSecond, "RadiansPerSecond", BaseUnits.Undefined), new UnitInfo(FrequencyUnit.Terahertz, "Terahertz", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Frequency); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -88,9 +84,6 @@ static Frequency() /// If value is NaN or Infinity. public Frequency(double value, FrequencyUnit unit) { - if (unit == FrequencyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -134,24 +127,6 @@ public Frequency(double value, UnitSystem unitSystem) /// public static FrequencyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Frequency - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Frequency MaxValue { get; } - - /// - /// Represents the smallest possible value of Frequency - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Frequency MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Frequency quantity. /// @@ -171,6 +146,9 @@ public Frequency(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -182,12 +160,6 @@ public Frequency(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Frequency; - /// /// The of this quantity. /// @@ -327,7 +299,7 @@ public static string GetAbbreviation(FrequencyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(FrequencyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -511,7 +483,7 @@ public static Frequency Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Frequency Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -542,7 +514,7 @@ public static bool TryParse(string? str, out Frequency result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Frequency result) { return QuantityParser.Default.TryParse( @@ -570,7 +542,7 @@ public static FrequencyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -596,7 +568,7 @@ public static bool TryParseUnit(string str, out FrequencyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out FrequencyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -676,20 +648,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Frequ return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Frequency left, Frequency right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Frequency left, Frequency right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -705,23 +663,6 @@ public int CompareTo(Frequency other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Frequency objFrequency)) - return false; - - return Equals(objFrequency); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Frequency other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Frequency within the given absolute or relative tolerance. @@ -767,7 +708,7 @@ public bool Equals(Frequency other, double tolerance, ComparisonType comparisonT if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -793,10 +734,9 @@ public override int GetHashCode() public double As(FrequencyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -817,10 +757,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is FrequencyUnit unitAsFrequencyUnit)) + if (!(unit is FrequencyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); - return As(unitAsFrequencyUnit); + return (double)As(typedUnit); } /// @@ -913,10 +853,10 @@ private bool TryToUnit(FrequencyUnit unit, out Frequency? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is FrequencyUnit unitAsFrequencyUnit)) + 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(unitAsFrequencyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -960,63 +900,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1098,8 +1004,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(FrequencyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Frequency.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Frequency.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs index dd10351b19..717ac2219a 100644 --- a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Fuel_efficiency /// [DataContract] - public readonly partial struct FuelEfficiency : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct FuelEfficiency : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static FuelEfficiency() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = FuelEfficiencyUnit.LiterPer100Kilometers; - MaxValue = new FuelEfficiency(double.MaxValue, BaseUnit); - MinValue = new FuelEfficiency(double.MinValue, BaseUnit); - QuantityType = QuantityType.FuelEfficiency; - Units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast().Except(new FuelEfficiencyUnit[]{ FuelEfficiencyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast().ToArray(); Zero = new FuelEfficiency(0, BaseUnit); Info = new QuantityInfo("FuelEfficiency", new UnitInfo[] @@ -70,7 +66,7 @@ static FuelEfficiency() new UnitInfo(FuelEfficiencyUnit.MilePerUkGallon, "MilesPerUkGallon", BaseUnits.Undefined), new UnitInfo(FuelEfficiencyUnit.MilePerUsGallon, "MilesPerUsGallon", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.FuelEfficiency); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static FuelEfficiency() /// If value is NaN or Infinity. public FuelEfficiency(double value, FuelEfficiencyUnit unit) { - if (unit == FuelEfficiencyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public FuelEfficiency(double value, UnitSystem unitSystem) /// public static FuelEfficiencyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of FuelEfficiency - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static FuelEfficiency MaxValue { get; } - - /// - /// Represents the smallest possible value of FuelEfficiency - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static FuelEfficiency MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the FuelEfficiency quantity. /// @@ -167,6 +142,9 @@ public FuelEfficiency(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public FuelEfficiency(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.FuelEfficiency; - /// /// The of this quantity. /// @@ -260,7 +232,7 @@ public static string GetAbbreviation(FuelEfficiencyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(FuelEfficiencyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -374,7 +346,7 @@ public static FuelEfficiency Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static FuelEfficiency Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -405,7 +377,7 @@ public static bool TryParse(string? str, out FuelEfficiency result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out FuelEfficiency result) { return QuantityParser.Default.TryParse( @@ -433,7 +405,7 @@ public static FuelEfficiencyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -459,7 +431,7 @@ public static bool TryParseUnit(string str, out FuelEfficiencyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out FuelEfficiencyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -539,20 +511,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out FuelE return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(FuelEfficiency left, FuelEfficiency right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(FuelEfficiency left, FuelEfficiency right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -568,23 +526,6 @@ public int CompareTo(FuelEfficiency other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is FuelEfficiency objFuelEfficiency)) - return false; - - return Equals(objFuelEfficiency); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(FuelEfficiency other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. @@ -630,7 +571,7 @@ public bool Equals(FuelEfficiency other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -656,10 +597,9 @@ public override int GetHashCode() public double As(FuelEfficiencyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -680,10 +620,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + if (!(unit is FuelEfficiencyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); - return As(unitAsFuelEfficiencyUnit); + return (double)As(typedUnit); } /// @@ -762,10 +702,10 @@ private bool TryToUnit(FuelEfficiencyUnit unit, out FuelEfficiency? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is FuelEfficiencyUnit unitAsFuelEfficiencyUnit)) + 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(unitAsFuelEfficiencyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -809,63 +749,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -947,8 +853,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(FuelEfficiencyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return FuelEfficiency.QuantityType; else if (conversionType == typeof(QuantityInfo)) return FuelEfficiency.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs index b5cdf0eea9..8bb0b3660b 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Heat flux is the flow of energy per unit of area per unit of time /// [DataContract] - public readonly partial struct HeatFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct HeatFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static HeatFlux() { BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); BaseUnit = HeatFluxUnit.WattPerSquareMeter; - MaxValue = new HeatFlux(double.MaxValue, BaseUnit); - MinValue = new HeatFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.HeatFlux; - Units = Enum.GetValues(typeof(HeatFluxUnit)).Cast().Except(new HeatFluxUnit[]{ HeatFluxUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(HeatFluxUnit)).Cast().ToArray(); Zero = new HeatFlux(0, BaseUnit); Info = new QuantityInfo("HeatFlux", new UnitInfo[] @@ -81,7 +77,7 @@ static HeatFlux() new UnitInfo(HeatFluxUnit.WattPerSquareInch, "WattsPerSquareInch", BaseUnits.Undefined), new UnitInfo(HeatFluxUnit.WattPerSquareMeter, "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.HeatFlux); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -95,9 +91,6 @@ static HeatFlux() /// If value is NaN or Infinity. public HeatFlux(double value, HeatFluxUnit unit) { - if (unit == HeatFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -141,24 +134,6 @@ public HeatFlux(double value, UnitSystem unitSystem) /// public static HeatFluxUnit BaseUnit { get; } - /// - /// Represents the largest possible value of HeatFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static HeatFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of HeatFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static HeatFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the HeatFlux quantity. /// @@ -178,6 +153,9 @@ public HeatFlux(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -189,12 +167,6 @@ public HeatFlux(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.HeatFlux; - /// /// The of this quantity. /// @@ -383,7 +355,7 @@ public static string GetAbbreviation(HeatFluxUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(HeatFluxUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -637,7 +609,7 @@ public static HeatFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static HeatFlux Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -668,7 +640,7 @@ public static bool TryParse(string? str, out HeatFlux result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out HeatFlux result) { return QuantityParser.Default.TryParse( @@ -696,7 +668,7 @@ public static HeatFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -722,7 +694,7 @@ public static bool TryParseUnit(string str, out HeatFluxUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatFluxUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -802,20 +774,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatF return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(HeatFlux left, HeatFlux right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(HeatFlux left, HeatFlux right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -831,23 +789,6 @@ public int CompareTo(HeatFlux other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is HeatFlux objHeatFlux)) - return false; - - return Equals(objHeatFlux); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(HeatFlux other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another HeatFlux within the given absolute or relative tolerance. @@ -893,7 +834,7 @@ public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -919,10 +860,9 @@ public override int GetHashCode() public double As(HeatFluxUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -943,10 +883,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is HeatFluxUnit unitAsHeatFluxUnit)) + if (!(unit is HeatFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); - return As(unitAsHeatFluxUnit); + return (double)As(typedUnit); } /// @@ -1053,10 +993,10 @@ private bool TryToUnit(HeatFluxUnit unit, out HeatFlux? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is HeatFluxUnit unitAsHeatFluxUnit)) + 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(unitAsHeatFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1100,63 +1040,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1238,8 +1144,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(HeatFluxUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return HeatFlux.QuantityType; else if (conversionType == typeof(QuantityInfo)) return HeatFlux.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index 9bb130b8db..648b980d75 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT) /// [DataContract] - public readonly partial struct HeatTransferCoefficient : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct HeatTransferCoefficient : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static HeatTransferCoefficient() { BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); BaseUnit = HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; - MaxValue = new HeatTransferCoefficient(double.MaxValue, BaseUnit); - MinValue = new HeatTransferCoefficient(double.MinValue, BaseUnit); - QuantityType = QuantityType.HeatTransferCoefficient; - Units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().Except(new HeatTransferCoefficientUnit[]{ HeatTransferCoefficientUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().ToArray(); Zero = new HeatTransferCoefficient(0, BaseUnit); Info = new QuantityInfo("HeatTransferCoefficient", new UnitInfo[] @@ -66,7 +62,7 @@ static HeatTransferCoefficient() new UnitInfo(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, "WattsPerSquareMeterCelsius", BaseUnits.Undefined), new UnitInfo(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, "WattsPerSquareMeterKelvin", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.HeatTransferCoefficient); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static HeatTransferCoefficient() /// If value is NaN or Infinity. public HeatTransferCoefficient(double value, HeatTransferCoefficientUnit unit) { - if (unit == HeatTransferCoefficientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) /// public static HeatTransferCoefficientUnit BaseUnit { get; } - /// - /// Represents the largest possible value of HeatTransferCoefficient - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static HeatTransferCoefficient MaxValue { get; } - - /// - /// Represents the smallest possible value of HeatTransferCoefficient - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static HeatTransferCoefficient MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the HeatTransferCoefficient quantity. /// @@ -163,6 +138,9 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.HeatTransferCoefficient; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(HeatTransferCoefficientUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(HeatTransferCoefficientUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static HeatTransferCoefficient Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static HeatTransferCoefficient Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out HeatTransferCoefficient result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out HeatTransferCoefficient result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static HeatTransferCoefficientUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatTransferCoefficientUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatT return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(HeatTransferCoefficient left, HeatTransferCoefficient right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(HeatTransferCoefficient left, HeatTransferCoefficient right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(HeatTransferCoefficient other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is HeatTransferCoefficient objHeatTransferCoefficient)) - return false; - - return Equals(objHeatTransferCoefficient); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(HeatTransferCoefficient other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another HeatTransferCoefficient within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(HeatTransferCoefficientUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is HeatTransferCoefficientUnit unitAsHeatTransferCoefficientUnit)) + if (!(unit is HeatTransferCoefficientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); - return As(unitAsHeatTransferCoefficientUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(HeatTransferCoefficientUnit unit, out HeatTransferCoeffic /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is HeatTransferCoefficientUnit unitAsHeatTransferCoefficientUnit)) + 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(unitAsHeatTransferCoefficientUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(HeatTransferCoefficientUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return HeatTransferCoefficient.QuantityType; else if (conversionType == typeof(QuantityInfo)) return HeatTransferCoefficient.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index ea69555d09..d3ddacb34a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Illuminance /// [DataContract] - public readonly partial struct Illuminance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Illuminance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Illuminance() { BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); BaseUnit = IlluminanceUnit.Lux; - MaxValue = new Illuminance(double.MaxValue, BaseUnit); - MinValue = new Illuminance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Illuminance; - Units = Enum.GetValues(typeof(IlluminanceUnit)).Cast().Except(new IlluminanceUnit[]{ IlluminanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(IlluminanceUnit)).Cast().ToArray(); Zero = new Illuminance(0, BaseUnit); Info = new QuantityInfo("Illuminance", new UnitInfo[] @@ -70,7 +66,7 @@ static Illuminance() new UnitInfo(IlluminanceUnit.Megalux, "Megalux", BaseUnits.Undefined), new UnitInfo(IlluminanceUnit.Millilux, "Millilux", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Illuminance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static Illuminance() /// If value is NaN or Infinity. public Illuminance(double value, IlluminanceUnit unit) { - if (unit == IlluminanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public Illuminance(double value, UnitSystem unitSystem) /// public static IlluminanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Illuminance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Illuminance MaxValue { get; } - - /// - /// Represents the smallest possible value of Illuminance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Illuminance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Illuminance quantity. /// @@ -167,6 +142,9 @@ public Illuminance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public Illuminance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Illuminance; - /// /// The of this quantity. /// @@ -260,7 +232,7 @@ public static string GetAbbreviation(IlluminanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(IlluminanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -374,7 +346,7 @@ public static Illuminance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Illuminance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -405,7 +377,7 @@ public static bool TryParse(string? str, out Illuminance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Illuminance result) { return QuantityParser.Default.TryParse( @@ -433,7 +405,7 @@ public static IlluminanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -459,7 +431,7 @@ public static bool TryParseUnit(string str, out IlluminanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out IlluminanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -539,20 +511,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Illum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Illuminance left, Illuminance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Illuminance left, Illuminance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -568,23 +526,6 @@ public int CompareTo(Illuminance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Illuminance objIlluminance)) - return false; - - return Equals(objIlluminance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Illuminance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Illuminance within the given absolute or relative tolerance. @@ -630,7 +571,7 @@ public bool Equals(Illuminance other, double tolerance, ComparisonType compariso if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -656,10 +597,9 @@ public override int GetHashCode() public double As(IlluminanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -680,10 +620,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is IlluminanceUnit unitAsIlluminanceUnit)) + if (!(unit is IlluminanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); - return As(unitAsIlluminanceUnit); + return (double)As(typedUnit); } /// @@ -762,10 +702,10 @@ private bool TryToUnit(IlluminanceUnit unit, out Illuminance? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is IlluminanceUnit unitAsIlluminanceUnit)) + 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(unitAsIlluminanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -809,63 +749,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -947,8 +853,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(IlluminanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Illuminance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Illuminance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index 8fb8d16c8e..809680f82d 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// [DataContract] - public readonly partial struct Information : IQuantity, IDecimalQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Information : IQuantity, IDecimalQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Information() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = InformationUnit.Bit; - MaxValue = new Information(decimal.MaxValue, BaseUnit); - MinValue = new Information(decimal.MinValue, BaseUnit); - QuantityType = QuantityType.Information; - Units = Enum.GetValues(typeof(InformationUnit)).Cast().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(InformationUnit)).Cast().ToArray(); Zero = new Information(0, BaseUnit); Info = new QuantityInfo("Information", new UnitInfo[] @@ -89,7 +85,7 @@ static Information() new UnitInfo(InformationUnit.Terabit, "Terabits", BaseUnits.Undefined), new UnitInfo(InformationUnit.Terabyte, "Terabytes", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Information); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -103,9 +99,6 @@ static Information() /// If value is NaN or Infinity. public Information(decimal value, InformationUnit unit) { - if (unit == InformationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = value; _unit = unit; } @@ -149,24 +142,6 @@ public Information(decimal value, UnitSystem unitSystem) /// public static InformationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Information - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Information MaxValue { get; } - - /// - /// Represents the smallest possible value of Information - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Information MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Information quantity. /// @@ -186,7 +161,8 @@ public Information(decimal value, UnitSystem unitSystem) /// public decimal Value => _value; - double IQuantity.Value => (double) _value; + /// + QuantityValue IQuantity.Value => _value; /// decimal IDecimalQuantity.Value => _value; @@ -202,12 +178,6 @@ public Information(decimal value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Information; - /// /// The of this quantity. /// @@ -218,134 +188,134 @@ public Information(decimal value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Bits => As(InformationUnit.Bit); + public decimal Bits => As(InformationUnit.Bit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Bytes => As(InformationUnit.Byte); + public decimal Bytes => As(InformationUnit.Byte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exabits => As(InformationUnit.Exabit); + public decimal Exabits => As(InformationUnit.Exabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exabytes => As(InformationUnit.Exabyte); + public decimal Exabytes => As(InformationUnit.Exabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exbibits => As(InformationUnit.Exbibit); + public decimal Exbibits => As(InformationUnit.Exbibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exbibytes => As(InformationUnit.Exbibyte); + public decimal Exbibytes => As(InformationUnit.Exbibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gibibits => As(InformationUnit.Gibibit); + public decimal Gibibits => As(InformationUnit.Gibibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gibibytes => As(InformationUnit.Gibibyte); + public decimal Gibibytes => As(InformationUnit.Gibibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigabits => As(InformationUnit.Gigabit); + public decimal Gigabits => As(InformationUnit.Gigabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigabytes => As(InformationUnit.Gigabyte); + public decimal Gigabytes => As(InformationUnit.Gigabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kibibits => As(InformationUnit.Kibibit); + public decimal Kibibits => As(InformationUnit.Kibibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kibibytes => As(InformationUnit.Kibibyte); + public decimal Kibibytes => As(InformationUnit.Kibibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilobits => As(InformationUnit.Kilobit); + public decimal Kilobits => As(InformationUnit.Kilobit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilobytes => As(InformationUnit.Kilobyte); + public decimal Kilobytes => As(InformationUnit.Kilobyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mebibits => As(InformationUnit.Mebibit); + public decimal Mebibits => As(InformationUnit.Mebibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mebibytes => As(InformationUnit.Mebibyte); + public decimal Mebibytes => As(InformationUnit.Mebibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megabits => As(InformationUnit.Megabit); + public decimal Megabits => As(InformationUnit.Megabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megabytes => As(InformationUnit.Megabyte); + public decimal Megabytes => As(InformationUnit.Megabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pebibits => As(InformationUnit.Pebibit); + public decimal Pebibits => As(InformationUnit.Pebibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pebibytes => As(InformationUnit.Pebibyte); + public decimal Pebibytes => As(InformationUnit.Pebibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petabits => As(InformationUnit.Petabit); + public decimal Petabits => As(InformationUnit.Petabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petabytes => As(InformationUnit.Petabyte); + public decimal Petabytes => As(InformationUnit.Petabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Tebibits => As(InformationUnit.Tebibit); + public decimal Tebibits => As(InformationUnit.Tebibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Tebibytes => As(InformationUnit.Tebibyte); + public decimal Tebibytes => As(InformationUnit.Tebibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terabits => As(InformationUnit.Terabit); + public decimal Terabits => As(InformationUnit.Terabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terabytes => As(InformationUnit.Terabyte); + public decimal Terabytes => As(InformationUnit.Terabyte); #endregion @@ -460,7 +430,7 @@ public static string GetAbbreviation(InformationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(InformationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -794,7 +764,7 @@ public static Information Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Information Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -825,7 +795,7 @@ public static bool TryParse(string? str, out Information result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Information result) { return QuantityParser.Default.TryParse( @@ -853,7 +823,7 @@ public static InformationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -879,7 +849,7 @@ public static bool TryParseUnit(string str, out InformationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out InformationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -926,7 +896,7 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Infor } /// Get ratio value from dividing by . - public static double operator /(Information left, Information right) + public static decimal operator /(Information left, Information right) { return left.Bits / right.Bits; } @@ -959,20 +929,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Infor return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Information left, Information right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Information left, Information right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -988,23 +944,6 @@ public int CompareTo(Information other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Information objInformation)) - return false; - - return Equals(objInformation); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Information other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Information within the given absolute or relative tolerance. @@ -1045,13 +984,13 @@ public bool Equals(Information other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Information other, double tolerance, ComparisonType comparisonType) + 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."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + decimal thisValue = this.Value; + decimal otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1073,17 +1012,21 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(InformationUnit unit) + public decimal As(InformationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; + + return ToUnit(unit).Value; + } - var converted = ToUnit(unit); - return (double)converted.Value; + double IQuantity.As(InformationUnit unit) + { + return (double)As(unit); } /// - public double As(UnitSystem unitSystem) + public decimal As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1097,13 +1040,19 @@ public double As(UnitSystem unitSystem) return As(firstUnitInfo.Value); } + /// + double IQuantity.As(UnitSystem unitSystem) + { + return (double)As(unitSystem); + } + /// double IQuantity.As(Enum unit) { - if (!(unit is InformationUnit unitAsInformationUnit)) + if (!(unit is InformationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); - return As(unitAsInformationUnit); + return (double)As(typedUnit); } /// @@ -1226,10 +1175,10 @@ private bool TryToUnit(InformationUnit unit, out Information? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is InformationUnit unitAsInformationUnit)) + 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(unitAsInformationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1273,63 +1222,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1411,8 +1326,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(InformationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Information.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Information.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index 282f3b7ee0..7d7da7a249 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. /// [DataContract] - public readonly partial struct Irradiance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Irradiance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Irradiance() { BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); BaseUnit = IrradianceUnit.WattPerSquareMeter; - MaxValue = new Irradiance(double.MaxValue, BaseUnit); - MinValue = new Irradiance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Irradiance; - Units = Enum.GetValues(typeof(IrradianceUnit)).Cast().Except(new IrradianceUnit[]{ IrradianceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(IrradianceUnit)).Cast().ToArray(); Zero = new Irradiance(0, BaseUnit); Info = new QuantityInfo("Irradiance", new UnitInfo[] @@ -77,7 +73,7 @@ static Irradiance() new UnitInfo(IrradianceUnit.WattPerSquareCentimeter, "WattsPerSquareCentimeter", BaseUnits.Undefined), new UnitInfo(IrradianceUnit.WattPerSquareMeter, "WattsPerSquareMeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Irradiance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -91,9 +87,6 @@ static Irradiance() /// If value is NaN or Infinity. public Irradiance(double value, IrradianceUnit unit) { - if (unit == IrradianceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -137,24 +130,6 @@ public Irradiance(double value, UnitSystem unitSystem) /// public static IrradianceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Irradiance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Irradiance MaxValue { get; } - - /// - /// Represents the smallest possible value of Irradiance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Irradiance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Irradiance quantity. /// @@ -174,6 +149,9 @@ public Irradiance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -185,12 +163,6 @@ public Irradiance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Irradiance; - /// /// The of this quantity. /// @@ -347,7 +319,7 @@ public static string GetAbbreviation(IrradianceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(IrradianceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -561,7 +533,7 @@ public static Irradiance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Irradiance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -592,7 +564,7 @@ public static bool TryParse(string? str, out Irradiance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Irradiance result) { return QuantityParser.Default.TryParse( @@ -620,7 +592,7 @@ public static IrradianceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -646,7 +618,7 @@ public static bool TryParseUnit(string str, out IrradianceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out IrradianceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -726,20 +698,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Irrad return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Irradiance left, Irradiance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Irradiance left, Irradiance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -755,23 +713,6 @@ public int CompareTo(Irradiance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Irradiance objIrradiance)) - return false; - - return Equals(objIrradiance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Irradiance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Irradiance within the given absolute or relative tolerance. @@ -817,7 +758,7 @@ public bool Equals(Irradiance other, double tolerance, ComparisonType comparison if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -843,10 +784,9 @@ public override int GetHashCode() public double As(IrradianceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -867,10 +807,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is IrradianceUnit unitAsIrradianceUnit)) + if (!(unit is IrradianceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); - return As(unitAsIrradianceUnit); + return (double)As(typedUnit); } /// @@ -969,10 +909,10 @@ private bool TryToUnit(IrradianceUnit unit, out Irradiance? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is IrradianceUnit unitAsIrradianceUnit)) + 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(unitAsIrradianceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1016,63 +956,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1154,8 +1060,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(IrradianceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Irradiance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Irradiance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index 7ff6478838..6377902a98 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Irradiation /// [DataContract] - public readonly partial struct Irradiation : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Irradiation : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Irradiation() { BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); BaseUnit = IrradiationUnit.JoulePerSquareMeter; - MaxValue = new Irradiation(double.MaxValue, BaseUnit); - MinValue = new Irradiation(double.MinValue, BaseUnit); - QuantityType = QuantityType.Irradiation; - Units = Enum.GetValues(typeof(IrradiationUnit)).Cast().Except(new IrradiationUnit[]{ IrradiationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(IrradiationUnit)).Cast().ToArray(); Zero = new Irradiation(0, BaseUnit); Info = new QuantityInfo("Irradiation", new UnitInfo[] @@ -73,7 +69,7 @@ static Irradiation() new UnitInfo(IrradiationUnit.MillijoulePerSquareCentimeter, "MillijoulesPerSquareCentimeter", BaseUnits.Undefined), new UnitInfo(IrradiationUnit.WattHourPerSquareMeter, "WattHoursPerSquareMeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Irradiation); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -87,9 +83,6 @@ static Irradiation() /// If value is NaN or Infinity. public Irradiation(double value, IrradiationUnit unit) { - if (unit == IrradiationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -133,24 +126,6 @@ public Irradiation(double value, UnitSystem unitSystem) /// public static IrradiationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Irradiation - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Irradiation MaxValue { get; } - - /// - /// Represents the smallest possible value of Irradiation - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Irradiation MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Irradiation quantity. /// @@ -170,6 +145,9 @@ public Irradiation(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -181,12 +159,6 @@ public Irradiation(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Irradiation; - /// /// The of this quantity. /// @@ -287,7 +259,7 @@ public static string GetAbbreviation(IrradiationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(IrradiationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -431,7 +403,7 @@ public static Irradiation Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Irradiation Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -462,7 +434,7 @@ public static bool TryParse(string? str, out Irradiation result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Irradiation result) { return QuantityParser.Default.TryParse( @@ -490,7 +462,7 @@ public static IrradiationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -516,7 +488,7 @@ public static bool TryParseUnit(string str, out IrradiationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out IrradiationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -596,20 +568,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Irrad return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Irradiation left, Irradiation right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Irradiation left, Irradiation right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -625,23 +583,6 @@ public int CompareTo(Irradiation other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Irradiation objIrradiation)) - return false; - - return Equals(objIrradiation); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Irradiation other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Irradiation within the given absolute or relative tolerance. @@ -687,7 +628,7 @@ public bool Equals(Irradiation other, double tolerance, ComparisonType compariso if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -713,10 +654,9 @@ public override int GetHashCode() public double As(IrradiationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -737,10 +677,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is IrradiationUnit unitAsIrradiationUnit)) + if (!(unit is IrradiationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); - return As(unitAsIrradiationUnit); + return (double)As(typedUnit); } /// @@ -825,10 +765,10 @@ private bool TryToUnit(IrradiationUnit unit, out Irradiation? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is IrradiationUnit unitAsIrradiationUnit)) + 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(unitAsIrradiationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -872,63 +812,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1010,8 +916,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(IrradiationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Irradiation.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Irradiation.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs index 3dc7352998..0b8bff3708 100644 --- a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,10 +32,10 @@ namespace UnitsNet { /// /// - /// Jerk or Jolt, in physics, is the rate at which the acceleration of an object changes over time. The SI unit for jerk is the Meter per second cubed (m/s³). Jerks are vector quantities (they have magnitude and direction) and add according to the parallelogram law. + /// /// [DataContract] - public readonly partial struct Jerk : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Jerk : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Jerk() { BaseDimensions = new BaseDimensions(1, 0, -3, 0, 0, 0, 0); BaseUnit = JerkUnit.MeterPerSecondCubed; - MaxValue = new Jerk(double.MaxValue, BaseUnit); - MinValue = new Jerk(double.MinValue, BaseUnit); - QuantityType = QuantityType.Jerk; - Units = Enum.GetValues(typeof(JerkUnit)).Cast().Except(new JerkUnit[]{ JerkUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(JerkUnit)).Cast().ToArray(); Zero = new Jerk(0, BaseUnit); Info = new QuantityInfo("Jerk", new UnitInfo[] @@ -74,7 +70,7 @@ static Jerk() new UnitInfo(JerkUnit.NanometerPerSecondCubed, "NanometersPerSecondCubed", BaseUnits.Undefined), new UnitInfo(JerkUnit.StandardGravitiesPerSecond, "StandardGravitiesPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Jerk); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -88,9 +84,6 @@ static Jerk() /// If value is NaN or Infinity. public Jerk(double value, JerkUnit unit) { - if (unit == JerkUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -134,24 +127,6 @@ public Jerk(double value, UnitSystem unitSystem) /// public static JerkUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Jerk - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Jerk MaxValue { get; } - - /// - /// Represents the smallest possible value of Jerk - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Jerk MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Jerk quantity. /// @@ -171,6 +146,9 @@ public Jerk(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -182,12 +160,6 @@ public Jerk(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Jerk; - /// /// The of this quantity. /// @@ -331,7 +303,7 @@ public static string GetAbbreviation(JerkUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(JerkUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -515,7 +487,7 @@ public static Jerk Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Jerk Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -546,7 +518,7 @@ public static bool TryParse(string? str, out Jerk result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Jerk result) { return QuantityParser.Default.TryParse( @@ -574,7 +546,7 @@ public static JerkUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -600,7 +572,7 @@ public static bool TryParseUnit(string str, out JerkUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out JerkUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -680,20 +652,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out JerkU return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Jerk left, Jerk right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Jerk left, Jerk right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -709,23 +667,6 @@ public int CompareTo(Jerk other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Jerk objJerk)) - return false; - - return Equals(objJerk); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Jerk other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Jerk within the given absolute or relative tolerance. @@ -771,7 +712,7 @@ 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 = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -797,10 +738,9 @@ public override int GetHashCode() public double As(JerkUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -821,10 +761,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is JerkUnit unitAsJerkUnit)) + if (!(unit is JerkUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(JerkUnit)} is supported.", nameof(unit)); - return As(unitAsJerkUnit); + return (double)As(typedUnit); } /// @@ -917,10 +857,10 @@ private bool TryToUnit(JerkUnit unit, out Jerk? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is JerkUnit unitAsJerkUnit)) + 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(unitAsJerkUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -964,63 +904,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1102,8 +1008,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(JerkUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Jerk.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Jerk.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index 7d37327964..a461b32e15 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Viscosity /// [DataContract] - public readonly partial struct KinematicViscosity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct KinematicViscosity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static KinematicViscosity() { BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); BaseUnit = KinematicViscosityUnit.SquareMeterPerSecond; - MaxValue = new KinematicViscosity(double.MaxValue, BaseUnit); - MinValue = new KinematicViscosity(double.MinValue, BaseUnit); - QuantityType = QuantityType.KinematicViscosity; - Units = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().Except(new KinematicViscosityUnit[]{ KinematicViscosityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().ToArray(); Zero = new KinematicViscosity(0, BaseUnit); Info = new QuantityInfo("KinematicViscosity", new UnitInfo[] @@ -75,7 +71,7 @@ static KinematicViscosity() new UnitInfo(KinematicViscosityUnit.SquareMeterPerSecond, "SquareMetersPerSecond", BaseUnits.Undefined), new UnitInfo(KinematicViscosityUnit.Stokes, "Stokes", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.KinematicViscosity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -89,9 +85,6 @@ static KinematicViscosity() /// If value is NaN or Infinity. public KinematicViscosity(double value, KinematicViscosityUnit unit) { - if (unit == KinematicViscosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -135,24 +128,6 @@ public KinematicViscosity(double value, UnitSystem unitSystem) /// public static KinematicViscosityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of KinematicViscosity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static KinematicViscosity MaxValue { get; } - - /// - /// Represents the smallest possible value of KinematicViscosity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static KinematicViscosity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the KinematicViscosity quantity. /// @@ -172,6 +147,9 @@ public KinematicViscosity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -183,12 +161,6 @@ public KinematicViscosity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.KinematicViscosity; - /// /// The of this quantity. /// @@ -313,7 +285,7 @@ public static string GetAbbreviation(KinematicViscosityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(KinematicViscosityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -477,7 +449,7 @@ public static KinematicViscosity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static KinematicViscosity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -508,7 +480,7 @@ public static bool TryParse(string? str, out KinematicViscosity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out KinematicViscosity result) { return QuantityParser.Default.TryParse( @@ -536,7 +508,7 @@ public static KinematicViscosityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -562,7 +534,7 @@ public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out KinematicViscosityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -642,20 +614,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Kinem return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(KinematicViscosity left, KinematicViscosity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(KinematicViscosity left, KinematicViscosity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -671,23 +629,6 @@ public int CompareTo(KinematicViscosity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is KinematicViscosity objKinematicViscosity)) - return false; - - return Equals(objKinematicViscosity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(KinematicViscosity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another KinematicViscosity within the given absolute or relative tolerance. @@ -733,7 +674,7 @@ public bool Equals(KinematicViscosity other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -759,10 +700,9 @@ public override int GetHashCode() public double As(KinematicViscosityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -783,10 +723,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is KinematicViscosityUnit unitAsKinematicViscosityUnit)) + if (!(unit is KinematicViscosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); - return As(unitAsKinematicViscosityUnit); + return (double)As(typedUnit); } /// @@ -875,10 +815,10 @@ private bool TryToUnit(KinematicViscosityUnit unit, out KinematicViscosity? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is KinematicViscosityUnit unitAsKinematicViscosityUnit)) + 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(unitAsKinematicViscosityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -922,63 +862,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1060,8 +966,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(KinematicViscosityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return KinematicViscosity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return KinematicViscosity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs index db0068527e..ba32a9e3a8 100644 --- a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -37,7 +36,7 @@ namespace UnitsNet /// [Obsolete("Use TemperatureGradient instead.")] [DataContract] - public readonly partial struct LapseRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct LapseRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -55,17 +54,14 @@ static LapseRate() { BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); BaseUnit = LapseRateUnit.DegreeCelsiusPerKilometer; - MaxValue = new LapseRate(double.MaxValue, BaseUnit); - MinValue = new LapseRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.LapseRate; - Units = Enum.GetValues(typeof(LapseRateUnit)).Cast().Except(new LapseRateUnit[]{ LapseRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LapseRateUnit)).Cast().ToArray(); Zero = new LapseRate(0, BaseUnit); Info = new QuantityInfo("LapseRate", new UnitInfo[] { new UnitInfo(LapseRateUnit.DegreeCelsiusPerKilometer, "DegreesCelciusPerKilometer", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.LapseRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -79,9 +75,6 @@ static LapseRate() /// If value is NaN or Infinity. public LapseRate(double value, LapseRateUnit unit) { - if (unit == LapseRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -125,24 +118,6 @@ public LapseRate(double value, UnitSystem unitSystem) /// public static LapseRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of LapseRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LapseRate MaxValue { get; } - - /// - /// Represents the smallest possible value of LapseRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LapseRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the LapseRate quantity. /// @@ -162,6 +137,9 @@ public LapseRate(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -173,12 +151,6 @@ public LapseRate(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.LapseRate; - /// /// The of this quantity. /// @@ -231,7 +203,7 @@ public static string GetAbbreviation(LapseRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LapseRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -315,7 +287,7 @@ public static LapseRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static LapseRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -346,7 +318,7 @@ public static bool TryParse(string? str, out LapseRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out LapseRate result) { return QuantityParser.Default.TryParse( @@ -374,7 +346,7 @@ public static LapseRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -400,7 +372,7 @@ public static bool TryParseUnit(string str, out LapseRateUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LapseRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -480,20 +452,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lapse return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(LapseRate left, LapseRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(LapseRate left, LapseRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -509,23 +467,6 @@ public int CompareTo(LapseRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is LapseRate objLapseRate)) - return false; - - return Equals(objLapseRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(LapseRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another LapseRate within the given absolute or relative tolerance. @@ -571,7 +512,7 @@ public bool Equals(LapseRate other, double tolerance, ComparisonType comparisonT if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -597,10 +538,9 @@ public override int GetHashCode() public double As(LapseRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -621,10 +561,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LapseRateUnit unitAsLapseRateUnit)) + if (!(unit is LapseRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit)); - return As(unitAsLapseRateUnit); + return (double)As(typedUnit); } /// @@ -697,10 +637,10 @@ private bool TryToUnit(LapseRateUnit unit, out LapseRate? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LapseRateUnit unitAsLapseRateUnit)) + if (!(unit is LapseRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LapseRateUnit)} is supported.", nameof(unit)); - return ToUnit(unitAsLapseRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -744,63 +684,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -882,8 +788,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LapseRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return LapseRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return LapseRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index d31ff1184d..b5632103e4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. /// [DataContract] - public readonly partial struct Length : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Length : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Length() { BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); BaseUnit = LengthUnit.Meter; - MaxValue = new Length(double.MaxValue, BaseUnit); - MinValue = new Length(double.MinValue, BaseUnit); - QuantityType = QuantityType.Length; - Units = Enum.GetValues(typeof(LengthUnit)).Cast().Except(new LengthUnit[]{ LengthUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LengthUnit)).Cast().ToArray(); Zero = new Length(0, BaseUnit); Info = new QuantityInfo("Length", new UnitInfo[] @@ -99,7 +95,7 @@ static Length() new UnitInfo(LengthUnit.UsSurveyFoot, "UsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)), new UnitInfo(LengthUnit.Yard, "Yards", new BaseUnits(length: LengthUnit.Yard)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Length); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -113,9 +109,6 @@ static Length() /// If value is NaN or Infinity. public Length(double value, LengthUnit unit) { - if (unit == LengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -159,24 +152,6 @@ public Length(double value, UnitSystem unitSystem) /// public static LengthUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Length - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Length MaxValue { get; } - - /// - /// Represents the smallest possible value of Length - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Length MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Length quantity. /// @@ -196,6 +171,9 @@ public Length(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -207,12 +185,6 @@ public Length(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Length; - /// /// The of this quantity. /// @@ -577,7 +549,7 @@ public static string GetAbbreviation(LengthUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LengthUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1011,7 +983,7 @@ public static Length Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Length Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1042,7 +1014,7 @@ public static bool TryParse(string? str, out Length result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Length result) { return QuantityParser.Default.TryParse( @@ -1070,7 +1042,7 @@ public static LengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1096,7 +1068,7 @@ public static bool TryParseUnit(string str, out LengthUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LengthUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1176,20 +1148,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lengt return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Length left, Length right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Length left, Length right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1205,23 +1163,6 @@ public int CompareTo(Length other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Length objLength)) - return false; - - return Equals(objLength); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Length other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Length within the given absolute or relative tolerance. @@ -1267,7 +1208,7 @@ public bool Equals(Length other, double tolerance, ComparisonType comparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1293,10 +1234,9 @@ public override int GetHashCode() public double As(LengthUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1317,10 +1257,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LengthUnit unitAsLengthUnit)) + if (!(unit is LengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); - return As(unitAsLengthUnit); + return (double)As(typedUnit); } /// @@ -1463,10 +1403,10 @@ private bool TryToUnit(LengthUnit unit, out Length? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LengthUnit unitAsLengthUnit)) + 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(unitAsLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1510,63 +1450,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1648,8 +1554,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LengthUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Length.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Length.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index 00db2ef221..66932378ee 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// [DataContract] - public readonly partial struct Level : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Level : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Level() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = LevelUnit.Decibel; - MaxValue = new Level(double.MaxValue, BaseUnit); - MinValue = new Level(double.MinValue, BaseUnit); - QuantityType = QuantityType.Level; - Units = Enum.GetValues(typeof(LevelUnit)).Cast().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LevelUnit)).Cast().ToArray(); Zero = new Level(0, BaseUnit); Info = new QuantityInfo("Level", new UnitInfo[] @@ -65,7 +61,7 @@ static Level() new UnitInfo(LevelUnit.Decibel, "Decibels", BaseUnits.Undefined), new UnitInfo(LevelUnit.Neper, "Nepers", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Level); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -79,9 +75,6 @@ static Level() /// If value is NaN or Infinity. public Level(double value, LevelUnit unit) { - if (unit == LevelUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -125,24 +118,6 @@ public Level(double value, UnitSystem unitSystem) /// public static LevelUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Level - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Level MaxValue { get; } - - /// - /// Represents the smallest possible value of Level - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Level MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Level quantity. /// @@ -162,6 +137,9 @@ public Level(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -173,12 +151,6 @@ public Level(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Level; - /// /// The of this quantity. /// @@ -239,7 +211,7 @@ public static string GetAbbreviation(LevelUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LevelUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -333,7 +305,7 @@ public static Level Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Level Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -364,7 +336,7 @@ public static bool TryParse(string? str, out Level result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Level result) { return QuantityParser.Default.TryParse( @@ -392,7 +364,7 @@ public static LevelUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -418,7 +390,7 @@ public static bool TryParseUnit(string str, out LevelUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LevelUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -506,20 +478,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Level return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Level left, Level right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Level left, Level right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -535,23 +493,6 @@ public int CompareTo(Level other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Level objLevel)) - return false; - - return Equals(objLevel); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Level other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Level within the given absolute or relative tolerance. @@ -597,7 +538,7 @@ public bool Equals(Level other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -623,10 +564,9 @@ public override int GetHashCode() public double As(LevelUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -647,10 +587,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LevelUnit unitAsLevelUnit)) + if (!(unit is LevelUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); - return As(unitAsLevelUnit); + return (double)As(typedUnit); } /// @@ -725,10 +665,10 @@ private bool TryToUnit(LevelUnit unit, out Level? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LevelUnit unitAsLevelUnit)) + 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(unitAsLevelUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -772,63 +712,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -910,8 +816,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LevelUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Level.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Level.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index 18ec504356..cb0e1870a2 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Linear_density /// [DataContract] - public readonly partial struct LinearDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct LinearDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static LinearDensity() { BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); BaseUnit = LinearDensityUnit.KilogramPerMeter; - MaxValue = new LinearDensity(double.MaxValue, BaseUnit); - MinValue = new LinearDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.LinearDensity; - Units = Enum.GetValues(typeof(LinearDensityUnit)).Cast().Except(new LinearDensityUnit[]{ LinearDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LinearDensityUnit)).Cast().ToArray(); Zero = new LinearDensity(0, BaseUnit); Info = new QuantityInfo("LinearDensity", new UnitInfo[] @@ -80,7 +76,7 @@ static LinearDensity() new UnitInfo(LinearDensityUnit.PoundPerFoot, "PoundsPerFoot", BaseUnits.Undefined), new UnitInfo(LinearDensityUnit.PoundPerInch, "PoundsPerInch", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.LinearDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -94,9 +90,6 @@ static LinearDensity() /// If value is NaN or Infinity. public LinearDensity(double value, LinearDensityUnit unit) { - if (unit == LinearDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -140,24 +133,6 @@ public LinearDensity(double value, UnitSystem unitSystem) /// public static LinearDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of LinearDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LinearDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of LinearDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LinearDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the LinearDensity quantity. /// @@ -177,6 +152,9 @@ public LinearDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -188,12 +166,6 @@ public LinearDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.LinearDensity; - /// /// The of this quantity. /// @@ -350,7 +322,7 @@ public static string GetAbbreviation(LinearDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LinearDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -564,7 +536,7 @@ public static LinearDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static LinearDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -595,7 +567,7 @@ public static bool TryParse(string? str, out LinearDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out LinearDensity result) { return QuantityParser.Default.TryParse( @@ -623,7 +595,7 @@ public static LinearDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -649,7 +621,7 @@ public static bool TryParseUnit(string str, out LinearDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LinearDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -729,20 +701,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Linea return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(LinearDensity left, LinearDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(LinearDensity left, LinearDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -758,23 +716,6 @@ public int CompareTo(LinearDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is LinearDensity objLinearDensity)) - return false; - - return Equals(objLinearDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(LinearDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another LinearDensity within the given absolute or relative tolerance. @@ -820,7 +761,7 @@ public bool Equals(LinearDensity other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -846,10 +787,9 @@ public override int GetHashCode() public double As(LinearDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -870,10 +810,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LinearDensityUnit unitAsLinearDensityUnit)) + if (!(unit is LinearDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); - return As(unitAsLinearDensityUnit); + return (double)As(typedUnit); } /// @@ -972,10 +912,10 @@ private bool TryToUnit(LinearDensityUnit unit, out LinearDensity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LinearDensityUnit unitAsLinearDensityUnit)) + 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(unitAsLinearDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1019,63 +959,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1157,8 +1063,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LinearDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return LinearDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return LinearDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs index bae0bffac8..331fea246d 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Linear_density /// [DataContract] - public readonly partial struct LinearPowerDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct LinearPowerDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static LinearPowerDensity() { BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); BaseUnit = LinearPowerDensityUnit.WattPerMeter; - MaxValue = new LinearPowerDensity(double.MaxValue, BaseUnit); - MinValue = new LinearPowerDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.LinearPowerDensity; - Units = Enum.GetValues(typeof(LinearPowerDensityUnit)).Cast().Except(new LinearPowerDensityUnit[]{ LinearPowerDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LinearPowerDensityUnit)).Cast().ToArray(); Zero = new LinearPowerDensity(0, BaseUnit); Info = new QuantityInfo("LinearPowerDensity", new UnitInfo[] @@ -91,7 +87,7 @@ static LinearPowerDensity() new UnitInfo(LinearPowerDensityUnit.WattPerMeter, "WattsPerMeter", BaseUnits.Undefined), new UnitInfo(LinearPowerDensityUnit.WattPerMillimeter, "WattsPerMillimeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.LinearPowerDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -105,9 +101,6 @@ static LinearPowerDensity() /// If value is NaN or Infinity. public LinearPowerDensity(double value, LinearPowerDensityUnit unit) { - if (unit == LinearPowerDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -151,24 +144,6 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) /// public static LinearPowerDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of LinearPowerDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LinearPowerDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of LinearPowerDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LinearPowerDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the LinearPowerDensity quantity. /// @@ -188,6 +163,9 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -199,12 +177,6 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.LinearPowerDensity; - /// /// The of this quantity. /// @@ -449,7 +421,7 @@ public static string GetAbbreviation(LinearPowerDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LinearPowerDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -773,7 +745,7 @@ public static LinearPowerDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static LinearPowerDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -804,7 +776,7 @@ public static bool TryParse(string? str, out LinearPowerDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out LinearPowerDensity result) { return QuantityParser.Default.TryParse( @@ -832,7 +804,7 @@ public static LinearPowerDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -858,7 +830,7 @@ public static bool TryParseUnit(string str, out LinearPowerDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LinearPowerDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -938,20 +910,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Linea return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(LinearPowerDensity left, LinearPowerDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(LinearPowerDensity left, LinearPowerDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -967,23 +925,6 @@ public int CompareTo(LinearPowerDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is LinearPowerDensity objLinearPowerDensity)) - return false; - - return Equals(objLinearPowerDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(LinearPowerDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another LinearPowerDensity within the given absolute or relative tolerance. @@ -1029,7 +970,7 @@ public bool Equals(LinearPowerDensity other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1055,10 +996,9 @@ public override int GetHashCode() public double As(LinearPowerDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1079,10 +1019,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LinearPowerDensityUnit unitAsLinearPowerDensityUnit)) + if (!(unit is LinearPowerDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); - return As(unitAsLinearPowerDensityUnit); + return (double)As(typedUnit); } /// @@ -1203,10 +1143,10 @@ private bool TryToUnit(LinearPowerDensityUnit unit, out LinearPowerDensity? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LinearPowerDensityUnit unitAsLinearPowerDensityUnit)) + 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(unitAsLinearPowerDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1250,63 +1190,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1388,8 +1294,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LinearPowerDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return LinearPowerDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return LinearPowerDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs index 1b82bb723b..ea20867ce4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,13 +32,13 @@ namespace UnitsNet { /// /// - /// Luminance is a photometric measure of the luminous intensity per unit area of light travelling in a given direction. + /// /// /// /// https://en.wikipedia.org/wiki/Luminance /// [DataContract] - public readonly partial struct Luminance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Luminance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Luminance() { BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); BaseUnit = LuminanceUnit.CandelaPerSquareMeter; - MaxValue = new Luminance(double.MaxValue, BaseUnit); - MinValue = new Luminance(double.MinValue, BaseUnit); - QuantityType = QuantityType.Luminance; - Units = Enum.GetValues(typeof(LuminanceUnit)).Cast().Except(new LuminanceUnit[]{ LuminanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LuminanceUnit)).Cast().ToArray(); Zero = new Luminance(0, BaseUnit); Info = new QuantityInfo("Luminance", new UnitInfo[] @@ -76,7 +72,7 @@ static Luminance() new UnitInfo(LuminanceUnit.NanocandelaPerSquareMeter, "NanocandelasPerSquareMeter", BaseUnits.Undefined), new UnitInfo(LuminanceUnit.Nit, "Nits", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Luminance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -90,9 +86,6 @@ static Luminance() /// If value is NaN or Infinity. public Luminance(double value, LuminanceUnit unit) { - if (unit == LuminanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -136,24 +129,6 @@ public Luminance(double value, UnitSystem unitSystem) /// public static LuminanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Luminance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Luminance MaxValue { get; } - - /// - /// Represents the smallest possible value of Luminance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Luminance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Luminance quantity. /// @@ -173,6 +148,9 @@ public Luminance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -184,12 +162,6 @@ public Luminance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Luminance; - /// /// The of this quantity. /// @@ -314,7 +286,7 @@ public static string GetAbbreviation(LuminanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LuminanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -488,7 +460,7 @@ public static Luminance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Luminance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -519,7 +491,7 @@ public static bool TryParse(string? str, out Luminance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Luminance result) { return QuantityParser.Default.TryParse( @@ -547,7 +519,7 @@ public static LuminanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -573,7 +545,7 @@ public static bool TryParseUnit(string str, out LuminanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -653,20 +625,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Luminance left, Luminance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Luminance left, Luminance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -682,23 +640,6 @@ public int CompareTo(Luminance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Luminance objLuminance)) - return false; - - return Equals(objLuminance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Luminance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Luminance within the given absolute or relative tolerance. @@ -744,7 +685,7 @@ public bool Equals(Luminance other, double tolerance, ComparisonType comparisonT if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -770,10 +711,9 @@ public override int GetHashCode() public double As(LuminanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -794,10 +734,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LuminanceUnit unitAsLuminanceUnit)) + if (!(unit is LuminanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminanceUnit)} is supported.", nameof(unit)); - return As(unitAsLuminanceUnit); + return (double)As(typedUnit); } /// @@ -888,10 +828,10 @@ private bool TryToUnit(LuminanceUnit unit, out Luminance? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminanceUnit unitAsLuminanceUnit)) + 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(unitAsLuminanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -935,63 +875,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1073,8 +979,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LuminanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Luminance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Luminance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs index 572eb6c751..90c81184ed 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminosity /// [DataContract] - public readonly partial struct Luminosity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Luminosity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Luminosity() { BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); BaseUnit = LuminosityUnit.Watt; - MaxValue = new Luminosity(double.MaxValue, BaseUnit); - MinValue = new Luminosity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Luminosity; - Units = Enum.GetValues(typeof(LuminosityUnit)).Cast().Except(new LuminosityUnit[]{ LuminosityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LuminosityUnit)).Cast().ToArray(); Zero = new Luminosity(0, BaseUnit); Info = new QuantityInfo("Luminosity", new UnitInfo[] @@ -80,7 +76,7 @@ static Luminosity() new UnitInfo(LuminosityUnit.Terawatt, "Terawatts", BaseUnits.Undefined), new UnitInfo(LuminosityUnit.Watt, "Watts", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Luminosity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -94,9 +90,6 @@ static Luminosity() /// If value is NaN or Infinity. public Luminosity(double value, LuminosityUnit unit) { - if (unit == LuminosityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -140,24 +133,6 @@ public Luminosity(double value, UnitSystem unitSystem) /// public static LuminosityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Luminosity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Luminosity MaxValue { get; } - - /// - /// Represents the smallest possible value of Luminosity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Luminosity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Luminosity quantity. /// @@ -177,6 +152,9 @@ public Luminosity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -188,12 +166,6 @@ public Luminosity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Luminosity; - /// /// The of this quantity. /// @@ -350,7 +322,7 @@ public static string GetAbbreviation(LuminosityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LuminosityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -564,7 +536,7 @@ public static Luminosity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Luminosity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -595,7 +567,7 @@ public static bool TryParse(string? str, out Luminosity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Luminosity result) { return QuantityParser.Default.TryParse( @@ -623,7 +595,7 @@ public static LuminosityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -649,7 +621,7 @@ public static bool TryParseUnit(string str, out LuminosityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminosityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -729,20 +701,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Luminosity left, Luminosity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Luminosity left, Luminosity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -758,23 +716,6 @@ public int CompareTo(Luminosity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Luminosity objLuminosity)) - return false; - - return Equals(objLuminosity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Luminosity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Luminosity within the given absolute or relative tolerance. @@ -820,7 +761,7 @@ public bool Equals(Luminosity other, double tolerance, ComparisonType comparison if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -846,10 +787,9 @@ public override int GetHashCode() public double As(LuminosityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -870,10 +810,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LuminosityUnit unitAsLuminosityUnit)) + if (!(unit is LuminosityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); - return As(unitAsLuminosityUnit); + return (double)As(typedUnit); } /// @@ -972,10 +912,10 @@ private bool TryToUnit(LuminosityUnit unit, out Luminosity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminosityUnit unitAsLuminosityUnit)) + 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(unitAsLuminosityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1019,63 +959,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1157,8 +1063,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LuminosityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Luminosity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Luminosity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index f53ed1d15f..8086454ba0 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminous_flux /// [DataContract] - public readonly partial struct LuminousFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct LuminousFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static LuminousFlux() { BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); BaseUnit = LuminousFluxUnit.Lumen; - MaxValue = new LuminousFlux(double.MaxValue, BaseUnit); - MinValue = new LuminousFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.LuminousFlux; - Units = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().Except(new LuminousFluxUnit[]{ LuminousFluxUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().ToArray(); Zero = new LuminousFlux(0, BaseUnit); Info = new QuantityInfo("LuminousFlux", new UnitInfo[] { new UnitInfo(LuminousFluxUnit.Lumen, "Lumens", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.LuminousFlux); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static LuminousFlux() /// If value is NaN or Infinity. public LuminousFlux(double value, LuminousFluxUnit unit) { - if (unit == LuminousFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public LuminousFlux(double value, UnitSystem unitSystem) /// public static LuminousFluxUnit BaseUnit { get; } - /// - /// Represents the largest possible value of LuminousFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LuminousFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of LuminousFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LuminousFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the LuminousFlux quantity. /// @@ -164,6 +139,9 @@ public LuminousFlux(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public LuminousFlux(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.LuminousFlux; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(LuminousFluxUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LuminousFluxUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static LuminousFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static LuminousFlux Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out LuminousFlux result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out LuminousFlux result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static LuminousFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out LuminousFluxUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminousFluxUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(LuminousFlux left, LuminousFlux right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(LuminousFlux left, LuminousFlux right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(LuminousFlux other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is LuminousFlux objLuminousFlux)) - return false; - - return Equals(objLuminousFlux); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(LuminousFlux other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another LuminousFlux within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(LuminousFluxUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LuminousFluxUnit unitAsLuminousFluxUnit)) + if (!(unit is LuminousFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); - return As(unitAsLuminousFluxUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(LuminousFluxUnit unit, out LuminousFlux? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminousFluxUnit unitAsLuminousFluxUnit)) + 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(unitAsLuminousFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LuminousFluxUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return LuminousFlux.QuantityType; else if (conversionType == typeof(QuantityInfo)) return LuminousFlux.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index 8287b378c0..e69fa0f73c 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminous_intensity /// [DataContract] - public readonly partial struct LuminousIntensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct LuminousIntensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static LuminousIntensity() { BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); BaseUnit = LuminousIntensityUnit.Candela; - MaxValue = new LuminousIntensity(double.MaxValue, BaseUnit); - MinValue = new LuminousIntensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.LuminousIntensity; - Units = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().Except(new LuminousIntensityUnit[]{ LuminousIntensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().ToArray(); Zero = new LuminousIntensity(0, BaseUnit); Info = new QuantityInfo("LuminousIntensity", new UnitInfo[] { new UnitInfo(LuminousIntensityUnit.Candela, "Candela", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.LuminousIntensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static LuminousIntensity() /// If value is NaN or Infinity. public LuminousIntensity(double value, LuminousIntensityUnit unit) { - if (unit == LuminousIntensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public LuminousIntensity(double value, UnitSystem unitSystem) /// public static LuminousIntensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of LuminousIntensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LuminousIntensity MaxValue { get; } - - /// - /// Represents the smallest possible value of LuminousIntensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static LuminousIntensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the LuminousIntensity quantity. /// @@ -164,6 +139,9 @@ public LuminousIntensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public LuminousIntensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.LuminousIntensity; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(LuminousIntensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(LuminousIntensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static LuminousIntensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static LuminousIntensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out LuminousIntensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out LuminousIntensity result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static LuminousIntensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminousIntensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Lumin return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(LuminousIntensity left, LuminousIntensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(LuminousIntensity left, LuminousIntensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(LuminousIntensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is LuminousIntensity objLuminousIntensity)) - return false; - - return Equals(objLuminousIntensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(LuminousIntensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another LuminousIntensity within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(LuminousIntensity other, double tolerance, ComparisonType com if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(LuminousIntensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is LuminousIntensityUnit unitAsLuminousIntensityUnit)) + if (!(unit is LuminousIntensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); - return As(unitAsLuminousIntensityUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(LuminousIntensityUnit unit, out LuminousIntensity? conver /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is LuminousIntensityUnit unitAsLuminousIntensityUnit)) + 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(unitAsLuminousIntensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(LuminousIntensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return LuminousIntensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return LuminousIntensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index 073423c734..2b7e0fa07f 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetic_field /// [DataContract] - public readonly partial struct MagneticField : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MagneticField : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static MagneticField() { BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); BaseUnit = MagneticFieldUnit.Tesla; - MaxValue = new MagneticField(double.MaxValue, BaseUnit); - MinValue = new MagneticField(double.MinValue, BaseUnit); - QuantityType = QuantityType.MagneticField; - Units = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().Except(new MagneticFieldUnit[]{ MagneticFieldUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().ToArray(); Zero = new MagneticField(0, BaseUnit); Info = new QuantityInfo("MagneticField", new UnitInfo[] @@ -72,7 +68,7 @@ static MagneticField() new UnitInfo(MagneticFieldUnit.Nanotesla, "Nanoteslas", BaseUnits.Undefined), new UnitInfo(MagneticFieldUnit.Tesla, "Teslas", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MagneticField); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -86,9 +82,6 @@ static MagneticField() /// If value is NaN or Infinity. public MagneticField(double value, MagneticFieldUnit unit) { - if (unit == MagneticFieldUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -132,24 +125,6 @@ public MagneticField(double value, UnitSystem unitSystem) /// public static MagneticFieldUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MagneticField - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MagneticField MaxValue { get; } - - /// - /// Represents the smallest possible value of MagneticField - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MagneticField MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MagneticField quantity. /// @@ -169,6 +144,9 @@ public MagneticField(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -180,12 +158,6 @@ public MagneticField(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MagneticField; - /// /// The of this quantity. /// @@ -278,7 +250,7 @@ public static string GetAbbreviation(MagneticFieldUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MagneticFieldUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -412,7 +384,7 @@ public static MagneticField Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MagneticField Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -443,7 +415,7 @@ public static bool TryParse(string? str, out MagneticField result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MagneticField result) { return QuantityParser.Default.TryParse( @@ -471,7 +443,7 @@ public static MagneticFieldUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -497,7 +469,7 @@ public static bool TryParseUnit(string str, out MagneticFieldUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MagneticFieldUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -577,20 +549,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MagneticField left, MagneticField right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MagneticField left, MagneticField right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -606,23 +564,6 @@ public int CompareTo(MagneticField other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MagneticField objMagneticField)) - return false; - - return Equals(objMagneticField); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MagneticField other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MagneticField within the given absolute or relative tolerance. @@ -668,7 +609,7 @@ public bool Equals(MagneticField other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -694,10 +635,9 @@ public override int GetHashCode() public double As(MagneticFieldUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -718,10 +658,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MagneticFieldUnit unitAsMagneticFieldUnit)) + if (!(unit is MagneticFieldUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); - return As(unitAsMagneticFieldUnit); + return (double)As(typedUnit); } /// @@ -804,10 +744,10 @@ private bool TryToUnit(MagneticFieldUnit unit, out MagneticField? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MagneticFieldUnit unitAsMagneticFieldUnit)) + 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(unitAsMagneticFieldUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -851,63 +791,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -989,8 +895,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MagneticFieldUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MagneticField.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MagneticField.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index 9dbfe323fb..8922d9f830 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetic_flux /// [DataContract] - public readonly partial struct MagneticFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MagneticFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static MagneticFlux() { BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); BaseUnit = MagneticFluxUnit.Weber; - MaxValue = new MagneticFlux(double.MaxValue, BaseUnit); - MinValue = new MagneticFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.MagneticFlux; - Units = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().Except(new MagneticFluxUnit[]{ MagneticFluxUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().ToArray(); Zero = new MagneticFlux(0, BaseUnit); Info = new QuantityInfo("MagneticFlux", new UnitInfo[] { new UnitInfo(MagneticFluxUnit.Weber, "Webers", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MagneticFlux); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static MagneticFlux() /// If value is NaN or Infinity. public MagneticFlux(double value, MagneticFluxUnit unit) { - if (unit == MagneticFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public MagneticFlux(double value, UnitSystem unitSystem) /// public static MagneticFluxUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MagneticFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MagneticFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of MagneticFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MagneticFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MagneticFlux quantity. /// @@ -164,6 +139,9 @@ public MagneticFlux(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public MagneticFlux(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MagneticFlux; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(MagneticFluxUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MagneticFluxUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static MagneticFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MagneticFlux Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out MagneticFlux result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MagneticFlux result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static MagneticFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out MagneticFluxUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MagneticFluxUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MagneticFlux left, MagneticFlux right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MagneticFlux left, MagneticFlux right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(MagneticFlux other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MagneticFlux objMagneticFlux)) - return false; - - return Equals(objMagneticFlux); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MagneticFlux other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MagneticFlux within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(MagneticFluxUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MagneticFluxUnit unitAsMagneticFluxUnit)) + if (!(unit is MagneticFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); - return As(unitAsMagneticFluxUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(MagneticFluxUnit unit, out MagneticFlux? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MagneticFluxUnit unitAsMagneticFluxUnit)) + 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(unitAsMagneticFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MagneticFluxUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MagneticFlux.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MagneticFlux.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index 069f6183b4..6038a986c4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetization /// [DataContract] - public readonly partial struct Magnetization : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Magnetization : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static Magnetization() { BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); BaseUnit = MagnetizationUnit.AmperePerMeter; - MaxValue = new Magnetization(double.MaxValue, BaseUnit); - MinValue = new Magnetization(double.MinValue, BaseUnit); - QuantityType = QuantityType.Magnetization; - Units = Enum.GetValues(typeof(MagnetizationUnit)).Cast().Except(new MagnetizationUnit[]{ MagnetizationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MagnetizationUnit)).Cast().ToArray(); Zero = new Magnetization(0, BaseUnit); Info = new QuantityInfo("Magnetization", new UnitInfo[] { new UnitInfo(MagnetizationUnit.AmperePerMeter, "AmperesPerMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Magnetization); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static Magnetization() /// If value is NaN or Infinity. public Magnetization(double value, MagnetizationUnit unit) { - if (unit == MagnetizationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public Magnetization(double value, UnitSystem unitSystem) /// public static MagnetizationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Magnetization - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Magnetization MaxValue { get; } - - /// - /// Represents the smallest possible value of Magnetization - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Magnetization MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Magnetization quantity. /// @@ -164,6 +139,9 @@ public Magnetization(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public Magnetization(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Magnetization; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(MagnetizationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MagnetizationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static Magnetization Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Magnetization Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out Magnetization result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Magnetization result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static MagnetizationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out MagnetizationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MagnetizationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Magne return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Magnetization left, Magnetization right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Magnetization left, Magnetization right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(Magnetization other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Magnetization objMagnetization)) - return false; - - return Equals(objMagnetization); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Magnetization other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Magnetization within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(Magnetization other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(MagnetizationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MagnetizationUnit unitAsMagnetizationUnit)) + if (!(unit is MagnetizationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); - return As(unitAsMagnetizationUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(MagnetizationUnit unit, out Magnetization? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MagnetizationUnit unitAsMagnetizationUnit)) + 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(unitAsMagnetizationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MagnetizationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Magnetization.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Magnetization.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index f5878f9b5e..4d07c98946 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In physics, mass (from Greek μᾶζα "barley cake, lump [of dough]") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg). /// [DataContract] - public readonly partial struct Mass : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Mass : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Mass() { BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); BaseUnit = MassUnit.Kilogram; - MaxValue = new Mass(double.MaxValue, BaseUnit); - MinValue = new Mass(double.MinValue, BaseUnit); - QuantityType = QuantityType.Mass; - Units = Enum.GetValues(typeof(MassUnit)).Cast().Except(new MassUnit[]{ MassUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MassUnit)).Cast().ToArray(); Zero = new Mass(0, BaseUnit); Info = new QuantityInfo("Mass", new UnitInfo[] @@ -88,7 +84,7 @@ static Mass() new UnitInfo(MassUnit.Stone, "Stone", new BaseUnits(mass: MassUnit.Stone)), new UnitInfo(MassUnit.Tonne, "Tonnes", new BaseUnits(mass: MassUnit.Tonne)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Mass); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -102,9 +98,6 @@ static Mass() /// If value is NaN or Infinity. public Mass(double value, MassUnit unit) { - if (unit == MassUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -148,24 +141,6 @@ public Mass(double value, UnitSystem unitSystem) /// public static MassUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Mass - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Mass MaxValue { get; } - - /// - /// Represents the smallest possible value of Mass - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Mass MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Mass quantity. /// @@ -185,6 +160,9 @@ public Mass(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -196,12 +174,6 @@ public Mass(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Mass; - /// /// The of this quantity. /// @@ -481,7 +453,7 @@ public static string GetAbbreviation(MassUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MassUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -805,7 +777,7 @@ public static Mass Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Mass Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -836,7 +808,7 @@ public static bool TryParse(string? str, out Mass result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Mass result) { return QuantityParser.Default.TryParse( @@ -864,7 +836,7 @@ public static MassUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -890,7 +862,7 @@ public static bool TryParseUnit(string str, out MassUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MassUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -970,20 +942,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassU return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Mass left, Mass right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Mass left, Mass right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -999,23 +957,6 @@ public int CompareTo(Mass other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Mass objMass)) - return false; - - return Equals(objMass); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Mass other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Mass within the given absolute or relative tolerance. @@ -1061,7 +1002,7 @@ public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1087,10 +1028,9 @@ public override int GetHashCode() public double As(MassUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1111,10 +1051,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MassUnit unitAsMassUnit)) + if (!(unit is MassUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); - return As(unitAsMassUnit); + return (double)As(typedUnit); } /// @@ -1235,10 +1175,10 @@ private bool TryToUnit(MassUnit unit, out Mass? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassUnit unitAsMassUnit)) + 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(unitAsMassUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1282,63 +1222,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1420,8 +1326,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MassUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Mass.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Mass.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs index 0de0bc6649..c608136eb3 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Mass_concentration_(chemistry) /// [DataContract] - public readonly partial struct MassConcentration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MassConcentration : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static MassConcentration() { BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); BaseUnit = MassConcentrationUnit.KilogramPerCubicMeter; - MaxValue = new MassConcentration(double.MaxValue, BaseUnit); - MinValue = new MassConcentration(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassConcentration; - Units = Enum.GetValues(typeof(MassConcentrationUnit)).Cast().Except(new MassConcentrationUnit[]{ MassConcentrationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MassConcentrationUnit)).Cast().ToArray(); Zero = new MassConcentration(0, BaseUnit); Info = new QuantityInfo("MassConcentration", new UnitInfo[] @@ -115,7 +111,7 @@ static MassConcentration() new UnitInfo(MassConcentrationUnit.TonnePerCubicMeter, "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)), new UnitInfo(MassConcentrationUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MassConcentration); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -129,9 +125,6 @@ static MassConcentration() /// If value is NaN or Infinity. public MassConcentration(double value, MassConcentrationUnit unit) { - if (unit == MassConcentrationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -175,24 +168,6 @@ public MassConcentration(double value, UnitSystem unitSystem) /// public static MassConcentrationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MassConcentration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassConcentration MaxValue { get; } - - /// - /// Represents the smallest possible value of MassConcentration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassConcentration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MassConcentration quantity. /// @@ -212,6 +187,9 @@ public MassConcentration(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -223,12 +201,6 @@ public MassConcentration(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MassConcentration; - /// /// The of this quantity. /// @@ -669,7 +641,7 @@ public static string GetAbbreviation(MassConcentrationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MassConcentrationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1233,7 +1205,7 @@ public static MassConcentration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MassConcentration Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1264,7 +1236,7 @@ public static bool TryParse(string? str, out MassConcentration result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MassConcentration result) { return QuantityParser.Default.TryParse( @@ -1292,7 +1264,7 @@ public static MassConcentrationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1318,7 +1290,7 @@ public static bool TryParseUnit(string str, out MassConcentrationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MassConcentrationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1398,20 +1370,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassC return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MassConcentration left, MassConcentration right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MassConcentration left, MassConcentration right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1427,23 +1385,6 @@ public int CompareTo(MassConcentration other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassConcentration objMassConcentration)) - return false; - - return Equals(objMassConcentration); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MassConcentration other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MassConcentration within the given absolute or relative tolerance. @@ -1489,7 +1430,7 @@ public bool Equals(MassConcentration other, double tolerance, ComparisonType com if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1515,10 +1456,9 @@ public override int GetHashCode() public double As(MassConcentrationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1539,10 +1479,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MassConcentrationUnit unitAsMassConcentrationUnit)) + if (!(unit is MassConcentrationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); - return As(unitAsMassConcentrationUnit); + return (double)As(typedUnit); } /// @@ -1711,10 +1651,10 @@ private bool TryToUnit(MassConcentrationUnit unit, out MassConcentration? conver /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassConcentrationUnit unitAsMassConcentrationUnit)) + 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(unitAsMassConcentrationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1758,63 +1698,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1896,8 +1802,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MassConcentrationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MassConcentration.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MassConcentration.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index 13cba9a06d..da50509547 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). /// [DataContract] - public readonly partial struct MassFlow : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MassFlow : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static MassFlow() { BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); BaseUnit = MassFlowUnit.GramPerSecond; - MaxValue = new MassFlow(double.MaxValue, BaseUnit); - MinValue = new MassFlow(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassFlow; - Units = Enum.GetValues(typeof(MassFlowUnit)).Cast().Except(new MassFlowUnit[]{ MassFlowUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MassFlowUnit)).Cast().ToArray(); Zero = new MassFlow(0, BaseUnit); Info = new QuantityInfo("MassFlow", new UnitInfo[] @@ -96,7 +92,7 @@ static MassFlow() new UnitInfo(MassFlowUnit.TonnePerDay, "TonnesPerDay", BaseUnits.Undefined), new UnitInfo(MassFlowUnit.TonnePerHour, "TonnesPerHour", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MassFlow); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -110,9 +106,6 @@ static MassFlow() /// If value is NaN or Infinity. public MassFlow(double value, MassFlowUnit unit) { - if (unit == MassFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -156,24 +149,6 @@ public MassFlow(double value, UnitSystem unitSystem) /// public static MassFlowUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MassFlow - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassFlow MaxValue { get; } - - /// - /// Represents the smallest possible value of MassFlow - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassFlow MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MassFlow quantity. /// @@ -193,6 +168,9 @@ public MassFlow(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -204,12 +182,6 @@ public MassFlow(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MassFlow; - /// /// The of this quantity. /// @@ -520,7 +492,7 @@ public static string GetAbbreviation(MassFlowUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MassFlowUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -924,7 +896,7 @@ public static MassFlow Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MassFlow Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -955,7 +927,7 @@ public static bool TryParse(string? str, out MassFlow result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MassFlow result) { return QuantityParser.Default.TryParse( @@ -983,7 +955,7 @@ public static MassFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1009,7 +981,7 @@ public static bool TryParseUnit(string str, out MassFlowUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MassFlowUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1089,20 +1061,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MassFlow left, MassFlow right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MassFlow left, MassFlow right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1118,23 +1076,6 @@ public int CompareTo(MassFlow other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassFlow objMassFlow)) - return false; - - return Equals(objMassFlow); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MassFlow other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MassFlow within the given absolute or relative tolerance. @@ -1180,7 +1121,7 @@ public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1206,10 +1147,9 @@ public override int GetHashCode() public double As(MassFlowUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1230,10 +1170,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MassFlowUnit unitAsMassFlowUnit)) + if (!(unit is MassFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); - return As(unitAsMassFlowUnit); + return (double)As(typedUnit); } /// @@ -1370,10 +1310,10 @@ private bool TryToUnit(MassFlowUnit unit, out MassFlow? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassFlowUnit unitAsMassFlowUnit)) + 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(unitAsMassFlowUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1417,63 +1357,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1555,8 +1461,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MassFlowUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MassFlow.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MassFlow.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index 0a2797e85b..cee7fb9244 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Mass flux is the mass flow rate per unit area. /// [DataContract] - public readonly partial struct MassFlux : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MassFlux : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static MassFlux() { BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); BaseUnit = MassFluxUnit.KilogramPerSecondPerSquareMeter; - MaxValue = new MassFlux(double.MaxValue, BaseUnit); - MinValue = new MassFlux(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassFlux; - Units = Enum.GetValues(typeof(MassFluxUnit)).Cast().Except(new MassFluxUnit[]{ MassFluxUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MassFluxUnit)).Cast().ToArray(); Zero = new MassFlux(0, BaseUnit); Info = new QuantityInfo("MassFlux", new UnitInfo[] @@ -75,7 +71,7 @@ static MassFlux() new UnitInfo(MassFluxUnit.KilogramPerSecondPerSquareMeter, "KilogramsPerSecondPerSquareMeter", BaseUnits.Undefined), new UnitInfo(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "KilogramsPerSecondPerSquareMillimeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MassFlux); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -89,9 +85,6 @@ static MassFlux() /// If value is NaN or Infinity. public MassFlux(double value, MassFluxUnit unit) { - if (unit == MassFluxUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -135,24 +128,6 @@ public MassFlux(double value, UnitSystem unitSystem) /// public static MassFluxUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MassFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassFlux MaxValue { get; } - - /// - /// Represents the smallest possible value of MassFlux - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassFlux MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MassFlux quantity. /// @@ -172,6 +147,9 @@ public MassFlux(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -183,12 +161,6 @@ public MassFlux(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MassFlux; - /// /// The of this quantity. /// @@ -329,7 +301,7 @@ public static string GetAbbreviation(MassFluxUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MassFluxUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -523,7 +495,7 @@ public static MassFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MassFlux Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -554,7 +526,7 @@ public static bool TryParse(string? str, out MassFlux result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MassFlux result) { return QuantityParser.Default.TryParse( @@ -582,7 +554,7 @@ public static MassFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -608,7 +580,7 @@ public static bool TryParseUnit(string str, out MassFluxUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MassFluxUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -688,20 +660,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MassFlux left, MassFlux right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MassFlux left, MassFlux right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -717,23 +675,6 @@ public int CompareTo(MassFlux other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassFlux objMassFlux)) - return false; - - return Equals(objMassFlux); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MassFlux other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MassFlux within the given absolute or relative tolerance. @@ -779,7 +720,7 @@ public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -805,10 +746,9 @@ public override int GetHashCode() public double As(MassFluxUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -829,10 +769,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MassFluxUnit unitAsMassFluxUnit)) + if (!(unit is MassFluxUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); - return As(unitAsMassFluxUnit); + return (double)As(typedUnit); } /// @@ -927,10 +867,10 @@ private bool TryToUnit(MassFluxUnit unit, out MassFlux? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassFluxUnit unitAsMassFluxUnit)) + 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(unitAsMassFluxUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -974,63 +914,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1112,8 +1018,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MassFluxUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MassFlux.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MassFlux.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs index f5eb200d78..b86c67e918 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Mass_fraction_(chemistry) /// [DataContract] - public readonly partial struct MassFraction : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MassFraction : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static MassFraction() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = MassFractionUnit.DecimalFraction; - MaxValue = new MassFraction(double.MaxValue, BaseUnit); - MinValue = new MassFraction(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassFraction; - Units = Enum.GetValues(typeof(MassFractionUnit)).Cast().Except(new MassFractionUnit[]{ MassFractionUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MassFractionUnit)).Cast().ToArray(); Zero = new MassFraction(0, BaseUnit); Info = new QuantityInfo("MassFraction", new UnitInfo[] @@ -90,7 +86,7 @@ static MassFraction() new UnitInfo(MassFractionUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined), new UnitInfo(MassFractionUnit.Percent, "Percent", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MassFraction); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -104,9 +100,6 @@ static MassFraction() /// If value is NaN or Infinity. public MassFraction(double value, MassFractionUnit unit) { - if (unit == MassFractionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -150,24 +143,6 @@ public MassFraction(double value, UnitSystem unitSystem) /// public static MassFractionUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MassFraction - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassFraction MaxValue { get; } - - /// - /// Represents the smallest possible value of MassFraction - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassFraction MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MassFraction quantity. /// @@ -187,6 +162,9 @@ public MassFraction(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -198,12 +176,6 @@ public MassFraction(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MassFraction; - /// /// The of this quantity. /// @@ -440,7 +412,7 @@ public static string GetAbbreviation(MassFractionUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MassFractionUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -754,7 +726,7 @@ public static MassFraction Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MassFraction Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -785,7 +757,7 @@ public static bool TryParse(string? str, out MassFraction result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MassFraction result) { return QuantityParser.Default.TryParse( @@ -813,7 +785,7 @@ public static MassFractionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -839,7 +811,7 @@ public static bool TryParseUnit(string str, out MassFractionUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MassFractionUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -919,20 +891,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassF return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MassFraction left, MassFraction right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MassFraction left, MassFraction right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -948,23 +906,6 @@ public int CompareTo(MassFraction other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassFraction objMassFraction)) - return false; - - return Equals(objMassFraction); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MassFraction other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MassFraction within the given absolute or relative tolerance. @@ -1010,7 +951,7 @@ public bool Equals(MassFraction other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1036,10 +977,9 @@ public override int GetHashCode() public double As(MassFractionUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1060,10 +1000,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MassFractionUnit unitAsMassFractionUnit)) + if (!(unit is MassFractionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); - return As(unitAsMassFractionUnit); + return (double)As(typedUnit); } /// @@ -1182,10 +1122,10 @@ private bool TryToUnit(MassFractionUnit unit, out MassFraction? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassFractionUnit unitAsMassFractionUnit)) + 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(unitAsMassFractionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1229,63 +1169,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1367,8 +1273,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MassFractionUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MassFraction.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MassFraction.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index 22e38296f1..4a882d33c4 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A property of body reflects how its mass is distributed with regard to an axis. /// [DataContract] - public readonly partial struct MassMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MassMomentOfInertia : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static MassMomentOfInertia() { BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); BaseUnit = MassMomentOfInertiaUnit.KilogramSquareMeter; - MaxValue = new MassMomentOfInertia(double.MaxValue, BaseUnit); - MinValue = new MassMomentOfInertia(double.MinValue, BaseUnit); - QuantityType = QuantityType.MassMomentOfInertia; - Units = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().Except(new MassMomentOfInertiaUnit[]{ MassMomentOfInertiaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().ToArray(); Zero = new MassMomentOfInertia(0, BaseUnit); Info = new QuantityInfo("MassMomentOfInertia", new UnitInfo[] @@ -91,7 +87,7 @@ static MassMomentOfInertia() new UnitInfo(MassMomentOfInertiaUnit.TonneSquareMeter, "TonneSquareMeters", BaseUnits.Undefined), new UnitInfo(MassMomentOfInertiaUnit.TonneSquareMilimeter, "TonneSquareMilimeters", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MassMomentOfInertia); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -105,9 +101,6 @@ static MassMomentOfInertia() /// If value is NaN or Infinity. public MassMomentOfInertia(double value, MassMomentOfInertiaUnit unit) { - if (unit == MassMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -151,24 +144,6 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) /// public static MassMomentOfInertiaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MassMomentOfInertia - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassMomentOfInertia MaxValue { get; } - - /// - /// Represents the smallest possible value of MassMomentOfInertia - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MassMomentOfInertia MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MassMomentOfInertia quantity. /// @@ -188,6 +163,9 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -199,12 +177,6 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MassMomentOfInertia; - /// /// The of this quantity. /// @@ -473,7 +445,7 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MassMomentOfInertiaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -827,7 +799,7 @@ public static MassMomentOfInertia Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MassMomentOfInertia Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -858,7 +830,7 @@ public static bool TryParse(string? str, out MassMomentOfInertia result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MassMomentOfInertia result) { return QuantityParser.Default.TryParse( @@ -886,7 +858,7 @@ public static MassMomentOfInertiaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -912,7 +884,7 @@ public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MassMomentOfInertiaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -992,20 +964,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out MassM return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1021,23 +979,6 @@ public int CompareTo(MassMomentOfInertia other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MassMomentOfInertia objMassMomentOfInertia)) - return false; - - return Equals(objMassMomentOfInertia); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MassMomentOfInertia other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MassMomentOfInertia within the given absolute or relative tolerance. @@ -1083,7 +1024,7 @@ public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1109,10 +1050,9 @@ public override int GetHashCode() public double As(MassMomentOfInertiaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1133,10 +1073,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MassMomentOfInertiaUnit unitAsMassMomentOfInertiaUnit)) + if (!(unit is MassMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); - return As(unitAsMassMomentOfInertiaUnit); + return (double)As(typedUnit); } /// @@ -1263,10 +1203,10 @@ private bool TryToUnit(MassMomentOfInertiaUnit unit, out MassMomentOfInertia? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MassMomentOfInertiaUnit unitAsMassMomentOfInertiaUnit)) + 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(unitAsMassMomentOfInertiaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1310,63 +1250,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1448,8 +1354,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MassMomentOfInertiaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MassMomentOfInertia.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MassMomentOfInertia.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index 76857c5838..90da0c7f02 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Molar energy is the amount of energy stored in 1 mole of a substance. /// [DataContract] - public readonly partial struct MolarEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MolarEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static MolarEnergy() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); BaseUnit = MolarEnergyUnit.JoulePerMole; - MaxValue = new MolarEnergy(double.MaxValue, BaseUnit); - MinValue = new MolarEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.MolarEnergy; - Units = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().Except(new MolarEnergyUnit[]{ MolarEnergyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().ToArray(); Zero = new MolarEnergy(0, BaseUnit); Info = new QuantityInfo("MolarEnergy", new UnitInfo[] @@ -66,7 +62,7 @@ static MolarEnergy() new UnitInfo(MolarEnergyUnit.KilojoulePerMole, "KilojoulesPerMole", BaseUnits.Undefined), new UnitInfo(MolarEnergyUnit.MegajoulePerMole, "MegajoulesPerMole", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MolarEnergy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static MolarEnergy() /// If value is NaN or Infinity. public MolarEnergy(double value, MolarEnergyUnit unit) { - if (unit == MolarEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public MolarEnergy(double value, UnitSystem unitSystem) /// public static MolarEnergyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MolarEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MolarEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of MolarEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MolarEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MolarEnergy quantity. /// @@ -163,6 +138,9 @@ public MolarEnergy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public MolarEnergy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MolarEnergy; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(MolarEnergyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MolarEnergyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static MolarEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MolarEnergy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out MolarEnergy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MolarEnergy result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static MolarEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out MolarEnergyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarEnergyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MolarEnergy left, MolarEnergy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MolarEnergy left, MolarEnergy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(MolarEnergy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MolarEnergy objMolarEnergy)) - return false; - - return Equals(objMolarEnergy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MolarEnergy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MolarEnergy within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(MolarEnergy other, double tolerance, ComparisonType compariso if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(MolarEnergyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MolarEnergyUnit unitAsMolarEnergyUnit)) + if (!(unit is MolarEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsMolarEnergyUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(MolarEnergyUnit unit, out MolarEnergy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarEnergyUnit unitAsMolarEnergyUnit)) + 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(unitAsMolarEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MolarEnergyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MolarEnergy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MolarEnergy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index b8d836f439..2dacb7ff7f 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. /// [DataContract] - public readonly partial struct MolarEntropy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MolarEntropy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static MolarEntropy() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); BaseUnit = MolarEntropyUnit.JoulePerMoleKelvin; - MaxValue = new MolarEntropy(double.MaxValue, BaseUnit); - MinValue = new MolarEntropy(double.MinValue, BaseUnit); - QuantityType = QuantityType.MolarEntropy; - Units = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().Except(new MolarEntropyUnit[]{ MolarEntropyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().ToArray(); Zero = new MolarEntropy(0, BaseUnit); Info = new QuantityInfo("MolarEntropy", new UnitInfo[] @@ -66,7 +62,7 @@ static MolarEntropy() new UnitInfo(MolarEntropyUnit.KilojoulePerMoleKelvin, "KilojoulesPerMoleKelvin", BaseUnits.Undefined), new UnitInfo(MolarEntropyUnit.MegajoulePerMoleKelvin, "MegajoulesPerMoleKelvin", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MolarEntropy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static MolarEntropy() /// If value is NaN or Infinity. public MolarEntropy(double value, MolarEntropyUnit unit) { - if (unit == MolarEntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public MolarEntropy(double value, UnitSystem unitSystem) /// public static MolarEntropyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MolarEntropy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MolarEntropy MaxValue { get; } - - /// - /// Represents the smallest possible value of MolarEntropy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MolarEntropy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MolarEntropy quantity. /// @@ -163,6 +138,9 @@ public MolarEntropy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public MolarEntropy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MolarEntropy; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(MolarEntropyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MolarEntropyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static MolarEntropy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MolarEntropy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out MolarEntropy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MolarEntropy result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static MolarEntropyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out MolarEntropyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarEntropyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MolarEntropy left, MolarEntropy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MolarEntropy left, MolarEntropy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(MolarEntropy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MolarEntropy objMolarEntropy)) - return false; - - return Equals(objMolarEntropy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MolarEntropy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MolarEntropy within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(MolarEntropyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MolarEntropyUnit unitAsMolarEntropyUnit)) + if (!(unit is MolarEntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); - return As(unitAsMolarEntropyUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(MolarEntropyUnit unit, out MolarEntropy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarEntropyUnit unitAsMolarEntropyUnit)) + 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(unitAsMolarEntropyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MolarEntropyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MolarEntropy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MolarEntropy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index 86b792d998..e8a3762dde 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance. /// [DataContract] - public readonly partial struct MolarMass : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct MolarMass : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static MolarMass() { BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); BaseUnit = MolarMassUnit.KilogramPerMole; - MaxValue = new MolarMass(double.MaxValue, BaseUnit); - MinValue = new MolarMass(double.MinValue, BaseUnit); - QuantityType = QuantityType.MolarMass; - Units = Enum.GetValues(typeof(MolarMassUnit)).Cast().Except(new MolarMassUnit[]{ MolarMassUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MolarMassUnit)).Cast().ToArray(); Zero = new MolarMass(0, BaseUnit); Info = new QuantityInfo("MolarMass", new UnitInfo[] @@ -75,7 +71,7 @@ static MolarMass() new UnitInfo(MolarMassUnit.NanogramPerMole, "NanogramsPerMole", BaseUnits.Undefined), new UnitInfo(MolarMassUnit.PoundPerMole, "PoundsPerMole", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.MolarMass); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -89,9 +85,6 @@ static MolarMass() /// If value is NaN or Infinity. public MolarMass(double value, MolarMassUnit unit) { - if (unit == MolarMassUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -135,24 +128,6 @@ public MolarMass(double value, UnitSystem unitSystem) /// public static MolarMassUnit BaseUnit { get; } - /// - /// Represents the largest possible value of MolarMass - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MolarMass MaxValue { get; } - - /// - /// Represents the smallest possible value of MolarMass - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static MolarMass MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the MolarMass quantity. /// @@ -172,6 +147,9 @@ public MolarMass(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -183,12 +161,6 @@ public MolarMass(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.MolarMass; - /// /// The of this quantity. /// @@ -341,7 +313,7 @@ public static string GetAbbreviation(MolarMassUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MolarMassUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -535,7 +507,7 @@ public static MolarMass Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static MolarMass Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -566,7 +538,7 @@ public static bool TryParse(string? str, out MolarMass result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out MolarMass result) { return QuantityParser.Default.TryParse( @@ -594,7 +566,7 @@ public static MolarMassUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -620,7 +592,7 @@ public static bool TryParseUnit(string str, out MolarMassUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarMassUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -700,20 +672,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(MolarMass left, MolarMass right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(MolarMass left, MolarMass right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -729,23 +687,6 @@ public int CompareTo(MolarMass other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is MolarMass objMolarMass)) - return false; - - return Equals(objMolarMass); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(MolarMass other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another MolarMass within the given absolute or relative tolerance. @@ -791,7 +732,7 @@ public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonT if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -817,10 +758,9 @@ public override int GetHashCode() public double As(MolarMassUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -841,10 +781,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MolarMassUnit unitAsMolarMassUnit)) + if (!(unit is MolarMassUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); - return As(unitAsMolarMassUnit); + return (double)As(typedUnit); } /// @@ -939,10 +879,10 @@ private bool TryToUnit(MolarMassUnit unit, out MolarMass? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarMassUnit unitAsMolarMassUnit)) + 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(unitAsMolarMassUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -986,63 +926,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1124,8 +1030,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MolarMassUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return MolarMass.QuantityType; else if (conversionType == typeof(QuantityInfo)) return MolarMass.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index ae66c68ee4..f9bb0590ca 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Molar_concentration /// [DataContract] - public readonly partial struct Molarity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Molarity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static Molarity() { BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); BaseUnit = MolarityUnit.MolesPerCubicMeter; - MaxValue = new Molarity(double.MaxValue, BaseUnit); - MinValue = new Molarity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Molarity; - Units = Enum.GetValues(typeof(MolarityUnit)).Cast().Except(new MolarityUnit[]{ MolarityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(MolarityUnit)).Cast().ToArray(); Zero = new Molarity(0, BaseUnit); Info = new QuantityInfo("Molarity", new UnitInfo[] @@ -83,7 +79,7 @@ static Molarity() new UnitInfo(MolarityUnit.PicomolePerLiter, "PicomolesPerLiter", BaseUnits.Undefined), new UnitInfo(MolarityUnit.PicomolesPerLiter, "PicomolesPerLiter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Molarity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -97,9 +93,6 @@ static Molarity() /// If value is NaN or Infinity. public Molarity(double value, MolarityUnit unit) { - if (unit == MolarityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -143,24 +136,6 @@ public Molarity(double value, UnitSystem unitSystem) /// public static MolarityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Molarity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Molarity MaxValue { get; } - - /// - /// Represents the smallest possible value of Molarity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Molarity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Molarity quantity. /// @@ -180,6 +155,9 @@ public Molarity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -191,12 +169,6 @@ public Molarity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Molarity; - /// /// The of this quantity. /// @@ -337,7 +309,7 @@ public static string GetAbbreviation(MolarityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(MolarityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -501,7 +473,7 @@ public static Molarity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Molarity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -532,7 +504,7 @@ public static bool TryParse(string? str, out Molarity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Molarity result) { return QuantityParser.Default.TryParse( @@ -560,7 +532,7 @@ public static MolarityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -586,7 +558,7 @@ public static bool TryParseUnit(string str, out MolarityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -666,20 +638,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Molar return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Molarity left, Molarity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Molarity left, Molarity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -695,23 +653,6 @@ public int CompareTo(Molarity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Molarity objMolarity)) - return false; - - return Equals(objMolarity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Molarity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Molarity within the given absolute or relative tolerance. @@ -757,7 +698,7 @@ public bool Equals(Molarity other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -783,10 +724,9 @@ public override int GetHashCode() public double As(MolarityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -807,10 +747,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is MolarityUnit unitAsMolarityUnit)) + if (!(unit is MolarityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); - return As(unitAsMolarityUnit); + return (double)As(typedUnit); } /// @@ -915,10 +855,10 @@ private bool TryToUnit(MolarityUnit unit, out Molarity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is MolarityUnit unitAsMolarityUnit)) + 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(unitAsMolarityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -962,63 +902,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1100,8 +1006,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(MolarityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Molarity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Molarity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index a13b4799f9..886fdcf5aa 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) /// [DataContract] - public readonly partial struct Permeability : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Permeability : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static Permeability() { BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); BaseUnit = PermeabilityUnit.HenryPerMeter; - MaxValue = new Permeability(double.MaxValue, BaseUnit); - MinValue = new Permeability(double.MinValue, BaseUnit); - QuantityType = QuantityType.Permeability; - Units = Enum.GetValues(typeof(PermeabilityUnit)).Cast().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PermeabilityUnit)).Cast().ToArray(); Zero = new Permeability(0, BaseUnit); Info = new QuantityInfo("Permeability", new UnitInfo[] { new UnitInfo(PermeabilityUnit.HenryPerMeter, "HenriesPerMeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Permeability); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static Permeability() /// If value is NaN or Infinity. public Permeability(double value, PermeabilityUnit unit) { - if (unit == PermeabilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public Permeability(double value, UnitSystem unitSystem) /// public static PermeabilityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Permeability - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Permeability MaxValue { get; } - - /// - /// Represents the smallest possible value of Permeability - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Permeability MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Permeability quantity. /// @@ -164,6 +139,9 @@ public Permeability(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public Permeability(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Permeability; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(PermeabilityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PermeabilityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static Permeability Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Permeability Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out Permeability result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Permeability result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static PermeabilityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out PermeabilityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PermeabilityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Perme return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Permeability left, Permeability right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Permeability left, Permeability right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(Permeability other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Permeability objPermeability)) - return false; - - return Equals(objPermeability); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Permeability other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Permeability within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(Permeability other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(PermeabilityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PermeabilityUnit unitAsPermeabilityUnit)) + if (!(unit is PermeabilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); - return As(unitAsPermeabilityUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(PermeabilityUnit unit, out Permeability? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PermeabilityUnit unitAsPermeabilityUnit)) + 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(unitAsPermeabilityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PermeabilityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Permeability.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Permeability.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index b62bc55c22..fe14ad749e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permittivity /// [DataContract] - public readonly partial struct Permittivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Permittivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static Permittivity() { BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); BaseUnit = PermittivityUnit.FaradPerMeter; - MaxValue = new Permittivity(double.MaxValue, BaseUnit); - MinValue = new Permittivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Permittivity; - Units = Enum.GetValues(typeof(PermittivityUnit)).Cast().Except(new PermittivityUnit[]{ PermittivityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PermittivityUnit)).Cast().ToArray(); Zero = new Permittivity(0, BaseUnit); Info = new QuantityInfo("Permittivity", new UnitInfo[] { new UnitInfo(PermittivityUnit.FaradPerMeter, "FaradsPerMeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Permittivity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static Permittivity() /// If value is NaN or Infinity. public Permittivity(double value, PermittivityUnit unit) { - if (unit == PermittivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public Permittivity(double value, UnitSystem unitSystem) /// public static PermittivityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Permittivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Permittivity MaxValue { get; } - - /// - /// Represents the smallest possible value of Permittivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Permittivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Permittivity quantity. /// @@ -164,6 +139,9 @@ public Permittivity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public Permittivity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Permittivity; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(PermittivityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PermittivityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static Permittivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Permittivity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out Permittivity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Permittivity result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static PermittivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out PermittivityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PermittivityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Permi return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Permittivity left, Permittivity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Permittivity left, Permittivity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(Permittivity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Permittivity objPermittivity)) - return false; - - return Equals(objPermittivity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Permittivity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Permittivity within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(Permittivity other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(PermittivityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PermittivityUnit unitAsPermittivityUnit)) + if (!(unit is PermittivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); - return As(unitAsPermittivityUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(PermittivityUnit unit, out Permittivity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PermittivityUnit unitAsPermittivityUnit)) + 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(unitAsPermittivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PermittivityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Permittivity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Permittivity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs index 4ffdab1f35..37425206e6 100644 --- a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,13 +32,13 @@ namespace UnitsNet { /// /// - /// In fluid mechanics, permeability is the measure of the ability of a porous material to allow fluids to pass through it. + /// /// /// /// https://en.wikipedia.org/wiki/Permeability_(Earth_sciences) /// [DataContract] - public readonly partial struct PorousMediumPermeability : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct PorousMediumPermeability : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static PorousMediumPermeability() { BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); BaseUnit = PorousMediumPermeabilityUnit.SquareMeter; - MaxValue = new PorousMediumPermeability(double.MaxValue, BaseUnit); - MinValue = new PorousMediumPermeability(double.MinValue, BaseUnit); - QuantityType = QuantityType.PorousMediumPermeability; - Units = Enum.GetValues(typeof(PorousMediumPermeabilityUnit)).Cast().Except(new PorousMediumPermeabilityUnit[]{ PorousMediumPermeabilityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PorousMediumPermeabilityUnit)).Cast().ToArray(); Zero = new PorousMediumPermeability(0, BaseUnit); Info = new QuantityInfo("PorousMediumPermeability", new UnitInfo[] @@ -71,7 +67,7 @@ static PorousMediumPermeability() new UnitInfo(PorousMediumPermeabilityUnit.SquareCentimeter, "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter)), new UnitInfo(PorousMediumPermeabilityUnit.SquareMeter, "SquareMeters", new BaseUnits(length: LengthUnit.Meter)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.PorousMediumPermeability); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -85,9 +81,6 @@ static PorousMediumPermeability() /// If value is NaN or Infinity. public PorousMediumPermeability(double value, PorousMediumPermeabilityUnit unit) { - if (unit == PorousMediumPermeabilityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -131,24 +124,6 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) /// public static PorousMediumPermeabilityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of PorousMediumPermeability - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PorousMediumPermeability MaxValue { get; } - - /// - /// Represents the smallest possible value of PorousMediumPermeability - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PorousMediumPermeability MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the PorousMediumPermeability quantity. /// @@ -168,6 +143,9 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -179,12 +157,6 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.PorousMediumPermeability; - /// /// The of this quantity. /// @@ -269,7 +241,7 @@ public static string GetAbbreviation(PorousMediumPermeabilityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PorousMediumPermeabilityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -393,7 +365,7 @@ public static PorousMediumPermeability Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static PorousMediumPermeability Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -424,7 +396,7 @@ public static bool TryParse(string? str, out PorousMediumPermeability result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out PorousMediumPermeability result) { return QuantityParser.Default.TryParse( @@ -452,7 +424,7 @@ public static PorousMediumPermeabilityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -478,7 +450,7 @@ public static bool TryParseUnit(string str, out PorousMediumPermeabilityUnit uni /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PorousMediumPermeabilityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -558,20 +530,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Porou return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(PorousMediumPermeability left, PorousMediumPermeability right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(PorousMediumPermeability left, PorousMediumPermeability right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -587,23 +545,6 @@ public int CompareTo(PorousMediumPermeability other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is PorousMediumPermeability objPorousMediumPermeability)) - return false; - - return Equals(objPorousMediumPermeability); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(PorousMediumPermeability other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another PorousMediumPermeability within the given absolute or relative tolerance. @@ -649,7 +590,7 @@ public bool Equals(PorousMediumPermeability other, double tolerance, ComparisonT if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -675,10 +616,9 @@ public override int GetHashCode() public double As(PorousMediumPermeabilityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -699,10 +639,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PorousMediumPermeabilityUnit unitAsPorousMediumPermeabilityUnit)) + if (!(unit is PorousMediumPermeabilityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} is supported.", nameof(unit)); - return As(unitAsPorousMediumPermeabilityUnit); + return (double)As(typedUnit); } /// @@ -783,10 +723,10 @@ private bool TryToUnit(PorousMediumPermeabilityUnit unit, out PorousMediumPermea /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PorousMediumPermeabilityUnit unitAsPorousMediumPermeabilityUnit)) + 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(unitAsPorousMediumPermeabilityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -830,63 +770,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -968,8 +874,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PorousMediumPermeabilityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return PorousMediumPermeability.QuantityType; else if (conversionType == typeof(QuantityInfo)) return PorousMediumPermeability.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index ccb66a7797..c79a8c8c91 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. /// [DataContract] - public readonly partial struct Power : IQuantity, IDecimalQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Power : IQuantity, IDecimalQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Power() { BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); BaseUnit = PowerUnit.Watt; - MaxValue = new Power(decimal.MaxValue, BaseUnit); - MinValue = new Power(decimal.MinValue, BaseUnit); - QuantityType = QuantityType.Power; - Units = Enum.GetValues(typeof(PowerUnit)).Cast().Except(new PowerUnit[]{ PowerUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PowerUnit)).Cast().ToArray(); Zero = new Power(0, BaseUnit); Info = new QuantityInfo("Power", new UnitInfo[] @@ -89,7 +85,7 @@ static Power() new UnitInfo(PowerUnit.Terawatt, "Terawatts", BaseUnits.Undefined), new UnitInfo(PowerUnit.Watt, "Watts", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Power); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -103,9 +99,6 @@ static Power() /// If value is NaN or Infinity. public Power(decimal value, PowerUnit unit) { - if (unit == PowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = value; _unit = unit; } @@ -149,24 +142,6 @@ public Power(decimal value, UnitSystem unitSystem) /// public static PowerUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Power - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Power MaxValue { get; } - - /// - /// Represents the smallest possible value of Power - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Power MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Power quantity. /// @@ -186,7 +161,8 @@ public Power(decimal value, UnitSystem unitSystem) /// public decimal Value => _value; - double IQuantity.Value => (double) _value; + /// + QuantityValue IQuantity.Value => _value; /// decimal IDecimalQuantity.Value => _value; @@ -202,12 +178,6 @@ public Power(decimal value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Power; - /// /// The of this quantity. /// @@ -218,134 +188,134 @@ public Power(decimal value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); + public decimal BoilerHorsepower => As(PowerUnit.BoilerHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); + public decimal BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decawatts => As(PowerUnit.Decawatt); + public decimal Decawatts => As(PowerUnit.Decawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Deciwatts => As(PowerUnit.Deciwatt); + public decimal Deciwatts => As(PowerUnit.Deciwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); + public decimal ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtowatts => As(PowerUnit.Femtowatt); + public decimal Femtowatts => As(PowerUnit.Femtowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); + public decimal GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigawatts => As(PowerUnit.Gigawatt); + public decimal Gigawatts => As(PowerUnit.Gigawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); + public decimal HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerHour => As(PowerUnit.JoulePerHour); + public decimal JoulesPerHour => As(PowerUnit.JoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); + public decimal KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); + public decimal KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilowatts => As(PowerUnit.Kilowatt); + public decimal Kilowatts => As(PowerUnit.Kilowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); + public decimal MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); + public decimal MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); + public decimal MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megawatts => As(PowerUnit.Megawatt); + public decimal Megawatts => As(PowerUnit.Megawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetricHorsepower => As(PowerUnit.MetricHorsepower); + public decimal MetricHorsepower => As(PowerUnit.MetricHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microwatts => As(PowerUnit.Microwatt); + public decimal Microwatts => As(PowerUnit.Microwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); + public decimal MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliwatts => As(PowerUnit.Milliwatt); + public decimal Milliwatts => As(PowerUnit.Milliwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanowatts => As(PowerUnit.Nanowatt); + public decimal Nanowatts => As(PowerUnit.Nanowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petawatts => As(PowerUnit.Petawatt); + public decimal Petawatts => As(PowerUnit.Petawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picowatts => As(PowerUnit.Picowatt); + public decimal Picowatts => As(PowerUnit.Picowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terawatts => As(PowerUnit.Terawatt); + public decimal Terawatts => As(PowerUnit.Terawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Watts => As(PowerUnit.Watt); + public decimal Watts => As(PowerUnit.Watt); #endregion @@ -460,7 +430,7 @@ public static string GetAbbreviation(PowerUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PowerUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -794,7 +764,7 @@ public static Power Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Power Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -825,7 +795,7 @@ public static bool TryParse(string? str, out Power result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Power result) { return QuantityParser.Default.TryParse( @@ -853,7 +823,7 @@ public static PowerUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -879,7 +849,7 @@ public static bool TryParseUnit(string str, out PowerUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PowerUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -926,7 +896,7 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power } /// Get ratio value from dividing by . - public static double operator /(Power left, Power right) + public static decimal operator /(Power left, Power right) { return left.Watts / right.Watts; } @@ -959,20 +929,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Power left, Power right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Power left, Power right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -988,23 +944,6 @@ public int CompareTo(Power other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Power objPower)) - return false; - - return Equals(objPower); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Power other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Power within the given absolute or relative tolerance. @@ -1045,13 +984,13 @@ public bool Equals(Power other) /// The absolute or relative tolerance value. Must be greater than or equal to 0. /// The comparison type: either relative or absolute. /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - public bool Equals(Power other, double tolerance, ComparisonType comparisonType) + 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."); - double thisValue = (double)this.Value; - double otherValueInThisUnits = other.As(this.Unit); + decimal thisValue = this.Value; + decimal otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } @@ -1073,17 +1012,21 @@ public override int GetHashCode() /// Convert to the unit representation . /// /// Value converted to the specified unit. - public double As(PowerUnit unit) + public decimal As(PowerUnit unit) { if (Unit == unit) - return (double)Value; + return Value; + + return ToUnit(unit).Value; + } - var converted = ToUnit(unit); - return (double)converted.Value; + double IQuantity.As(PowerUnit unit) + { + return (double)As(unit); } /// - public double As(UnitSystem unitSystem) + public decimal As(UnitSystem unitSystem) { if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); @@ -1097,13 +1040,19 @@ public double As(UnitSystem unitSystem) return As(firstUnitInfo.Value); } + /// + double IQuantity.As(UnitSystem unitSystem) + { + return (double)As(unitSystem); + } + /// double IQuantity.As(Enum unit) { - if (!(unit is PowerUnit unitAsPowerUnit)) + if (!(unit is PowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); - return As(unitAsPowerUnit); + return (double)As(typedUnit); } /// @@ -1165,7 +1114,7 @@ private bool TryToUnit(PowerUnit unit, out Power? converted) { // PowerUnit -> BaseUnit (PowerUnit.BoilerHorsepower, PowerUnit.Watt) => new Power(_value * 9812.5m, PowerUnit.Watt), - (PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt) => new Power(_value * 0.293071m, 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), @@ -1174,11 +1123,11 @@ private bool TryToUnit(PowerUnit unit, out Power? converted) (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.293071m) * 1e3m, 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.293071m) * 1e6m, 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), @@ -1192,7 +1141,7 @@ private bool TryToUnit(PowerUnit unit, out Power? converted) // BaseUnit -> PowerUnit (PowerUnit.Watt, PowerUnit.BoilerHorsepower) => new Power(_value / 9812.5m, PowerUnit.BoilerHorsepower), - (PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour) => new Power(_value / 0.293071m, PowerUnit.BritishThermalUnitPerHour), + (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), @@ -1201,11 +1150,11 @@ private bool TryToUnit(PowerUnit unit, out Power? converted) (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.293071m) / 1e3m, PowerUnit.KilobritishThermalUnitPerHour), + (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.293071m) / 1e6m, PowerUnit.MegabritishThermalUnitPerHour), + (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), @@ -1226,10 +1175,10 @@ private bool TryToUnit(PowerUnit unit, out Power? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PowerUnit unitAsPowerUnit)) + 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(unitAsPowerUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1273,63 +1222,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1411,8 +1326,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PowerUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Power.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Power.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs index ef42b24ca2..070beb332d 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The amount of power in a volume. /// [DataContract] - public readonly partial struct PowerDensity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct PowerDensity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static PowerDensity() { BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); BaseUnit = PowerDensityUnit.WattPerCubicMeter; - MaxValue = new PowerDensity(double.MaxValue, BaseUnit); - MinValue = new PowerDensity(double.MinValue, BaseUnit); - QuantityType = QuantityType.PowerDensity; - Units = Enum.GetValues(typeof(PowerDensityUnit)).Cast().Except(new PowerDensityUnit[]{ PowerDensityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PowerDensityUnit)).Cast().ToArray(); Zero = new PowerDensity(0, BaseUnit); Info = new QuantityInfo("PowerDensity", new UnitInfo[] @@ -107,7 +103,7 @@ static PowerDensity() new UnitInfo(PowerDensityUnit.WattPerCubicMeter, "WattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), new UnitInfo(PowerDensityUnit.WattPerLiter, "WattsPerLiter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.PowerDensity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -121,9 +117,6 @@ static PowerDensity() /// If value is NaN or Infinity. public PowerDensity(double value, PowerDensityUnit unit) { - if (unit == PowerDensityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -167,24 +160,6 @@ public PowerDensity(double value, UnitSystem unitSystem) /// public static PowerDensityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of PowerDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PowerDensity MaxValue { get; } - - /// - /// Represents the smallest possible value of PowerDensity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PowerDensity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the PowerDensity quantity. /// @@ -204,6 +179,9 @@ public PowerDensity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -215,12 +193,6 @@ public PowerDensity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.PowerDensity; - /// /// The of this quantity. /// @@ -617,7 +589,7 @@ public static string GetAbbreviation(PowerDensityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PowerDensityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1131,7 +1103,7 @@ public static PowerDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static PowerDensity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1162,7 +1134,7 @@ public static bool TryParse(string? str, out PowerDensity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out PowerDensity result) { return QuantityParser.Default.TryParse( @@ -1190,7 +1162,7 @@ public static PowerDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1216,7 +1188,7 @@ public static bool TryParseUnit(string str, out PowerDensityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PowerDensityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1296,20 +1268,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(PowerDensity left, PowerDensity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(PowerDensity left, PowerDensity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1325,23 +1283,6 @@ public int CompareTo(PowerDensity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is PowerDensity objPowerDensity)) - return false; - - return Equals(objPowerDensity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(PowerDensity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another PowerDensity within the given absolute or relative tolerance. @@ -1387,7 +1328,7 @@ public bool Equals(PowerDensity other, double tolerance, ComparisonType comparis if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1413,10 +1354,9 @@ public override int GetHashCode() public double As(PowerDensityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1437,10 +1377,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PowerDensityUnit unitAsPowerDensityUnit)) + if (!(unit is PowerDensityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); - return As(unitAsPowerDensityUnit); + return (double)As(typedUnit); } /// @@ -1599,10 +1539,10 @@ private bool TryToUnit(PowerDensityUnit unit, out PowerDensity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PowerDensityUnit unitAsPowerDensityUnit)) + 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(unitAsPowerDensityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1646,63 +1586,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1784,8 +1690,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PowerDensityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return PowerDensity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return PowerDensity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index 58d56dbddf..21c7d7b2c8 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The strength of a signal expressed in decibels (dB) relative to one watt. /// [DataContract] - public readonly partial struct PowerRatio : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct PowerRatio : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static PowerRatio() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = PowerRatioUnit.DecibelWatt; - MaxValue = new PowerRatio(double.MaxValue, BaseUnit); - MinValue = new PowerRatio(double.MinValue, BaseUnit); - QuantityType = QuantityType.PowerRatio; - Units = Enum.GetValues(typeof(PowerRatioUnit)).Cast().Except(new PowerRatioUnit[]{ PowerRatioUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PowerRatioUnit)).Cast().ToArray(); Zero = new PowerRatio(0, BaseUnit); Info = new QuantityInfo("PowerRatio", new UnitInfo[] @@ -65,7 +61,7 @@ static PowerRatio() new UnitInfo(PowerRatioUnit.DecibelMilliwatt, "DecibelMilliwatts", BaseUnits.Undefined), new UnitInfo(PowerRatioUnit.DecibelWatt, "DecibelWatts", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.PowerRatio); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -79,9 +75,6 @@ static PowerRatio() /// If value is NaN or Infinity. public PowerRatio(double value, PowerRatioUnit unit) { - if (unit == PowerRatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -125,24 +118,6 @@ public PowerRatio(double value, UnitSystem unitSystem) /// public static PowerRatioUnit BaseUnit { get; } - /// - /// Represents the largest possible value of PowerRatio - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PowerRatio MaxValue { get; } - - /// - /// Represents the smallest possible value of PowerRatio - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PowerRatio MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the PowerRatio quantity. /// @@ -162,6 +137,9 @@ public PowerRatio(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -173,12 +151,6 @@ public PowerRatio(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.PowerRatio; - /// /// The of this quantity. /// @@ -239,7 +211,7 @@ public static string GetAbbreviation(PowerRatioUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PowerRatioUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -333,7 +305,7 @@ public static PowerRatio Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static PowerRatio Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -364,7 +336,7 @@ public static bool TryParse(string? str, out PowerRatio result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out PowerRatio result) { return QuantityParser.Default.TryParse( @@ -392,7 +364,7 @@ public static PowerRatioUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -418,7 +390,7 @@ public static bool TryParseUnit(string str, out PowerRatioUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PowerRatioUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -506,20 +478,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Power return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(PowerRatio left, PowerRatio right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(PowerRatio left, PowerRatio right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -535,23 +493,6 @@ public int CompareTo(PowerRatio other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is PowerRatio objPowerRatio)) - return false; - - return Equals(objPowerRatio); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(PowerRatio other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another PowerRatio within the given absolute or relative tolerance. @@ -597,7 +538,7 @@ public bool Equals(PowerRatio other, double tolerance, ComparisonType comparison if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -623,10 +564,9 @@ public override int GetHashCode() public double As(PowerRatioUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -647,10 +587,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PowerRatioUnit unitAsPowerRatioUnit)) + if (!(unit is PowerRatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); - return As(unitAsPowerRatioUnit); + return (double)As(typedUnit); } /// @@ -725,10 +665,10 @@ private bool TryToUnit(PowerRatioUnit unit, out PowerRatio? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PowerRatioUnit unitAsPowerRatioUnit)) + 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(unitAsPowerRatioUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -772,63 +712,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -910,8 +816,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PowerRatioUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return PowerRatio.QuantityType; else if (conversionType == typeof(QuantityInfo)) return PowerRatio.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index ab3b022c1f..de40801b2f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa). /// [DataContract] - public readonly partial struct Pressure : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Pressure : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Pressure() { BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); BaseUnit = PressureUnit.Pascal; - MaxValue = new Pressure(double.MaxValue, BaseUnit); - MinValue = new Pressure(double.MinValue, BaseUnit); - QuantityType = QuantityType.Pressure; - Units = Enum.GetValues(typeof(PressureUnit)).Cast().Except(new PressureUnit[]{ PressureUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PressureUnit)).Cast().ToArray(); Zero = new Pressure(0, BaseUnit); Info = new QuantityInfo("Pressure", new UnitInfo[] @@ -110,7 +106,7 @@ static Pressure() new UnitInfo(PressureUnit.TonneForcePerSquareMillimeter, "TonnesForcePerSquareMillimeter", BaseUnits.Undefined), new UnitInfo(PressureUnit.Torr, "Torrs", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Pressure); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -124,9 +120,6 @@ static Pressure() /// If value is NaN or Infinity. public Pressure(double value, PressureUnit unit) { - if (unit == PressureUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -170,24 +163,6 @@ public Pressure(double value, UnitSystem unitSystem) /// public static PressureUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Pressure - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Pressure MaxValue { get; } - - /// - /// Represents the smallest possible value of Pressure - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Pressure MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Pressure quantity. /// @@ -207,6 +182,9 @@ public Pressure(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -218,12 +196,6 @@ public Pressure(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Pressure; - /// /// The of this quantity. /// @@ -675,7 +647,7 @@ public static string GetAbbreviation(PressureUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PressureUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1219,7 +1191,7 @@ public static Pressure Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Pressure Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1250,7 +1222,7 @@ public static bool TryParse(string? str, out Pressure result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Pressure result) { return QuantityParser.Default.TryParse( @@ -1278,7 +1250,7 @@ public static PressureUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1304,7 +1276,7 @@ public static bool TryParseUnit(string str, out PressureUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PressureUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1384,20 +1356,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Press return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Pressure left, Pressure right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Pressure left, Pressure right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1413,23 +1371,6 @@ public int CompareTo(Pressure other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Pressure objPressure)) - return false; - - return Equals(objPressure); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Pressure other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Pressure within the given absolute or relative tolerance. @@ -1475,7 +1416,7 @@ public bool Equals(Pressure other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1501,10 +1442,9 @@ public override int GetHashCode() public double As(PressureUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1525,10 +1465,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PressureUnit unitAsPressureUnit)) + if (!(unit is PressureUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); - return As(unitAsPressureUnit); + return (double)As(typedUnit); } /// @@ -1693,10 +1633,10 @@ private bool TryToUnit(PressureUnit unit, out Pressure? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PressureUnit unitAsPressureUnit)) + 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(unitAsPressureUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1740,63 +1680,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1878,8 +1784,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PressureUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Pressure.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Pressure.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index 278cc4b639..5c34d5763d 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time). /// [DataContract] - public readonly partial struct PressureChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct PressureChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static PressureChangeRate() { BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); BaseUnit = PressureChangeRateUnit.PascalPerSecond; - MaxValue = new PressureChangeRate(double.MaxValue, BaseUnit); - MinValue = new PressureChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.PressureChangeRate; - Units = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().Except(new PressureChangeRateUnit[]{ PressureChangeRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().ToArray(); Zero = new PressureChangeRate(0, BaseUnit); Info = new QuantityInfo("PressureChangeRate", new UnitInfo[] @@ -77,7 +73,7 @@ static PressureChangeRate() new UnitInfo(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "PoundsForcePerSquareInchPerMinute", BaseUnits.Undefined), new UnitInfo(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "PoundsForcePerSquareInchPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.PressureChangeRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -91,9 +87,6 @@ static PressureChangeRate() /// If value is NaN or Infinity. public PressureChangeRate(double value, PressureChangeRateUnit unit) { - if (unit == PressureChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -137,24 +130,6 @@ public PressureChangeRate(double value, UnitSystem unitSystem) /// public static PressureChangeRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of PressureChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PressureChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of PressureChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static PressureChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the PressureChangeRate quantity. /// @@ -174,6 +149,9 @@ public PressureChangeRate(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -185,12 +163,6 @@ public PressureChangeRate(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.PressureChangeRate; - /// /// The of this quantity. /// @@ -361,7 +333,7 @@ public static string GetAbbreviation(PressureChangeRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(PressureChangeRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -575,7 +547,7 @@ public static PressureChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static PressureChangeRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -606,7 +578,7 @@ public static bool TryParse(string? str, out PressureChangeRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out PressureChangeRate result) { return QuantityParser.Default.TryParse( @@ -634,7 +606,7 @@ public static PressureChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -660,7 +632,7 @@ public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out PressureChangeRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -740,20 +712,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Press return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(PressureChangeRate left, PressureChangeRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(PressureChangeRate left, PressureChangeRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -769,23 +727,6 @@ public int CompareTo(PressureChangeRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is PressureChangeRate objPressureChangeRate)) - return false; - - return Equals(objPressureChangeRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(PressureChangeRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another PressureChangeRate within the given absolute or relative tolerance. @@ -831,7 +772,7 @@ public bool Equals(PressureChangeRate other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -857,10 +798,9 @@ public override int GetHashCode() public double As(PressureChangeRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -881,10 +821,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is PressureChangeRateUnit unitAsPressureChangeRateUnit)) + if (!(unit is PressureChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsPressureChangeRateUnit); + return (double)As(typedUnit); } /// @@ -983,10 +923,10 @@ private bool TryToUnit(PressureChangeRateUnit unit, out PressureChangeRate? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is PressureChangeRateUnit unitAsPressureChangeRateUnit)) + 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(unitAsPressureChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1030,63 +970,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1168,8 +1074,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(PressureChangeRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return PressureChangeRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return PressureChangeRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index e448ed574c..4c4fc5bed4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as "a to b" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer). /// [DataContract] - public readonly partial struct Ratio : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Ratio : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Ratio() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = RatioUnit.DecimalFraction; - MaxValue = new Ratio(double.MaxValue, BaseUnit); - MinValue = new Ratio(double.MinValue, BaseUnit); - QuantityType = QuantityType.Ratio; - Units = Enum.GetValues(typeof(RatioUnit)).Cast().Except(new RatioUnit[]{ RatioUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RatioUnit)).Cast().ToArray(); Zero = new Ratio(0, BaseUnit); Info = new QuantityInfo("Ratio", new UnitInfo[] @@ -69,7 +65,7 @@ static Ratio() new UnitInfo(RatioUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined), new UnitInfo(RatioUnit.Percent, "Percent", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Ratio); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static Ratio() /// If value is NaN or Infinity. public Ratio(double value, RatioUnit unit) { - if (unit == RatioUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public Ratio(double value, UnitSystem unitSystem) /// public static RatioUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Ratio - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Ratio MaxValue { get; } - - /// - /// Represents the smallest possible value of Ratio - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Ratio MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Ratio quantity. /// @@ -166,6 +141,9 @@ public Ratio(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public Ratio(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Ratio; - /// /// The of this quantity. /// @@ -275,7 +247,7 @@ public static string GetAbbreviation(RatioUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RatioUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -409,7 +381,7 @@ public static Ratio Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Ratio Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -440,7 +412,7 @@ public static bool TryParse(string? str, out Ratio result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Ratio result) { return QuantityParser.Default.TryParse( @@ -468,7 +440,7 @@ public static RatioUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -494,7 +466,7 @@ public static bool TryParseUnit(string str, out RatioUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RatioUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -574,20 +546,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ratio return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Ratio left, Ratio right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Ratio left, Ratio right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -603,23 +561,6 @@ public int CompareTo(Ratio other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Ratio objRatio)) - return false; - - return Equals(objRatio); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Ratio other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Ratio within the given absolute or relative tolerance. @@ -665,7 +606,7 @@ public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -691,10 +632,9 @@ public override int GetHashCode() public double As(RatioUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -715,10 +655,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RatioUnit unitAsRatioUnit)) + if (!(unit is RatioUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); - return As(unitAsRatioUnit); + return (double)As(typedUnit); } /// @@ -801,10 +741,10 @@ private bool TryToUnit(RatioUnit unit, out Ratio? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RatioUnit unitAsRatioUnit)) + 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(unitAsRatioUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -848,63 +788,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -986,8 +892,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RatioUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Ratio.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Ratio.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs index b67b710f68..f295a579c7 100644 --- a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The change in ratio per unit of time. /// [DataContract] - public readonly partial struct RatioChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct RatioChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static RatioChangeRate() { BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); BaseUnit = RatioChangeRateUnit.DecimalFractionPerSecond; - MaxValue = new RatioChangeRate(double.MaxValue, BaseUnit); - MinValue = new RatioChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.RatioChangeRate; - Units = Enum.GetValues(typeof(RatioChangeRateUnit)).Cast().Except(new RatioChangeRateUnit[]{ RatioChangeRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RatioChangeRateUnit)).Cast().ToArray(); Zero = new RatioChangeRate(0, BaseUnit); Info = new QuantityInfo("RatioChangeRate", new UnitInfo[] @@ -65,7 +61,7 @@ static RatioChangeRate() new UnitInfo(RatioChangeRateUnit.DecimalFractionPerSecond, "DecimalFractionsPerSecond", BaseUnits.Undefined), new UnitInfo(RatioChangeRateUnit.PercentPerSecond, "PercentsPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.RatioChangeRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -79,9 +75,6 @@ static RatioChangeRate() /// If value is NaN or Infinity. public RatioChangeRate(double value, RatioChangeRateUnit unit) { - if (unit == RatioChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -125,24 +118,6 @@ public RatioChangeRate(double value, UnitSystem unitSystem) /// public static RatioChangeRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of RatioChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RatioChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of RatioChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RatioChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the RatioChangeRate quantity. /// @@ -162,6 +137,9 @@ public RatioChangeRate(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -173,12 +151,6 @@ public RatioChangeRate(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.RatioChangeRate; - /// /// The of this quantity. /// @@ -239,7 +211,7 @@ public static string GetAbbreviation(RatioChangeRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RatioChangeRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -333,7 +305,7 @@ public static RatioChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static RatioChangeRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -364,7 +336,7 @@ public static bool TryParse(string? str, out RatioChangeRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out RatioChangeRate result) { return QuantityParser.Default.TryParse( @@ -392,7 +364,7 @@ public static RatioChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -418,7 +390,7 @@ public static bool TryParseUnit(string str, out RatioChangeRateUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RatioChangeRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -498,20 +470,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Ratio return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(RatioChangeRate left, RatioChangeRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(RatioChangeRate left, RatioChangeRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -527,23 +485,6 @@ public int CompareTo(RatioChangeRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is RatioChangeRate objRatioChangeRate)) - return false; - - return Equals(objRatioChangeRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(RatioChangeRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another RatioChangeRate within the given absolute or relative tolerance. @@ -589,7 +530,7 @@ public bool Equals(RatioChangeRate other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -615,10 +556,9 @@ public override int GetHashCode() public double As(RatioChangeRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -639,10 +579,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RatioChangeRateUnit unitAsRatioChangeRateUnit)) + if (!(unit is RatioChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsRatioChangeRateUnit); + return (double)As(typedUnit); } /// @@ -717,10 +657,10 @@ private bool TryToUnit(RatioChangeRateUnit unit, out RatioChangeRate? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RatioChangeRateUnit unitAsRatioChangeRateUnit)) + 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(unitAsRatioChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -764,63 +704,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -902,8 +808,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RatioChangeRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return RatioChangeRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return RatioChangeRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs index 25ea9007f2..ad7a4923c5 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. /// [DataContract] - public readonly partial struct ReactiveEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ReactiveEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ReactiveEnergy() { BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); BaseUnit = ReactiveEnergyUnit.VoltampereReactiveHour; - MaxValue = new ReactiveEnergy(double.MaxValue, BaseUnit); - MinValue = new ReactiveEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReactiveEnergy; - Units = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().ToArray(); Zero = new ReactiveEnergy(0, BaseUnit); Info = new QuantityInfo("ReactiveEnergy", new UnitInfo[] @@ -66,7 +62,7 @@ static ReactiveEnergy() new UnitInfo(ReactiveEnergyUnit.MegavoltampereReactiveHour, "MegavoltampereReactiveHours", BaseUnits.Undefined), new UnitInfo(ReactiveEnergyUnit.VoltampereReactiveHour, "VoltampereReactiveHours", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ReactiveEnergy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static ReactiveEnergy() /// If value is NaN or Infinity. public ReactiveEnergy(double value, ReactiveEnergyUnit unit) { - if (unit == ReactiveEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) /// public static ReactiveEnergyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ReactiveEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReactiveEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of ReactiveEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReactiveEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ReactiveEnergy quantity. /// @@ -163,6 +138,9 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ReactiveEnergy; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ReactiveEnergyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static ReactiveEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ReactiveEnergy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out ReactiveEnergy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ReactiveEnergy result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static ReactiveEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ReactiveEnergyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out React return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(ReactiveEnergy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReactiveEnergy objReactiveEnergy)) - return false; - - return Equals(objReactiveEnergy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ReactiveEnergy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ReactiveEnergy within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(ReactiveEnergy other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(ReactiveEnergyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) + if (!(unit is ReactiveEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsReactiveEnergyUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(ReactiveEnergyUnit unit, out ReactiveEnergy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) + 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(unitAsReactiveEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ReactiveEnergyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ReactiveEnergy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ReactiveEnergy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs index ef084b7591..8755488de6 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase. /// [DataContract] - public readonly partial struct ReactivePower : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ReactivePower : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ReactivePower() { BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); BaseUnit = ReactivePowerUnit.VoltampereReactive; - MaxValue = new ReactivePower(double.MaxValue, BaseUnit); - MinValue = new ReactivePower(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReactivePower; - Units = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().Except(new ReactivePowerUnit[]{ ReactivePowerUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().ToArray(); Zero = new ReactivePower(0, BaseUnit); Info = new QuantityInfo("ReactivePower", new UnitInfo[] @@ -67,7 +63,7 @@ static ReactivePower() new UnitInfo(ReactivePowerUnit.MegavoltampereReactive, "MegavoltamperesReactive", BaseUnits.Undefined), new UnitInfo(ReactivePowerUnit.VoltampereReactive, "VoltamperesReactive", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ReactivePower); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static ReactivePower() /// If value is NaN or Infinity. public ReactivePower(double value, ReactivePowerUnit unit) { - if (unit == ReactivePowerUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public ReactivePower(double value, UnitSystem unitSystem) /// public static ReactivePowerUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ReactivePower - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReactivePower MaxValue { get; } - - /// - /// Represents the smallest possible value of ReactivePower - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReactivePower MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ReactivePower quantity. /// @@ -164,6 +139,9 @@ public ReactivePower(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public ReactivePower(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ReactivePower; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(ReactivePowerUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ReactivePowerUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static ReactivePower Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ReactivePower Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out ReactivePower result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ReactivePower result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static ReactivePowerUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out ReactivePowerUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ReactivePowerUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -536,20 +508,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out React return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ReactivePower left, ReactivePower right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ReactivePower left, ReactivePower right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -565,23 +523,6 @@ public int CompareTo(ReactivePower other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReactivePower objReactivePower)) - return false; - - return Equals(objReactivePower); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ReactivePower other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ReactivePower within the given absolute or relative tolerance. @@ -627,7 +568,7 @@ public bool Equals(ReactivePower other, double tolerance, ComparisonType compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -653,10 +594,9 @@ public override int GetHashCode() public double As(ReactivePowerUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -677,10 +617,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ReactivePowerUnit unitAsReactivePowerUnit)) + if (!(unit is ReactivePowerUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); - return As(unitAsReactivePowerUnit); + return (double)As(typedUnit); } /// @@ -759,10 +699,10 @@ private bool TryToUnit(ReactivePowerUnit unit, out ReactivePower? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReactivePowerUnit unitAsReactivePowerUnit)) + 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(unitAsReactivePowerUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -806,63 +746,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -944,8 +850,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ReactivePowerUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ReactivePower.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ReactivePower.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs index 7679482725..3f02a59653 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Inverse-square_law /// [DataContract] - public readonly partial struct ReciprocalArea : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ReciprocalArea : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ReciprocalArea() { BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); BaseUnit = ReciprocalAreaUnit.InverseSquareMeter; - MaxValue = new ReciprocalArea(double.MaxValue, BaseUnit); - MinValue = new ReciprocalArea(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReciprocalArea; - Units = Enum.GetValues(typeof(ReciprocalAreaUnit)).Cast().Except(new ReciprocalAreaUnit[]{ ReciprocalAreaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ReciprocalAreaUnit)).Cast().ToArray(); Zero = new ReciprocalArea(0, BaseUnit); Info = new QuantityInfo("ReciprocalArea", new UnitInfo[] @@ -77,7 +73,7 @@ static ReciprocalArea() new UnitInfo(ReciprocalAreaUnit.InverseSquareYard, "InverseSquareYards", BaseUnits.Undefined), new UnitInfo(ReciprocalAreaUnit.InverseUsSurveySquareFoot, "InverseUsSurveySquareFeet", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ReciprocalArea); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -91,9 +87,6 @@ static ReciprocalArea() /// If value is NaN or Infinity. public ReciprocalArea(double value, ReciprocalAreaUnit unit) { - if (unit == ReciprocalAreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -137,24 +130,6 @@ public ReciprocalArea(double value, UnitSystem unitSystem) /// public static ReciprocalAreaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ReciprocalArea - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReciprocalArea MaxValue { get; } - - /// - /// Represents the smallest possible value of ReciprocalArea - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReciprocalArea MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ReciprocalArea quantity. /// @@ -174,6 +149,9 @@ public ReciprocalArea(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -185,12 +163,6 @@ public ReciprocalArea(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ReciprocalArea; - /// /// The of this quantity. /// @@ -323,7 +295,7 @@ public static string GetAbbreviation(ReciprocalAreaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ReciprocalAreaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -507,7 +479,7 @@ public static ReciprocalArea Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ReciprocalArea Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -538,7 +510,7 @@ public static bool TryParse(string? str, out ReciprocalArea result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ReciprocalArea result) { return QuantityParser.Default.TryParse( @@ -566,7 +538,7 @@ public static ReciprocalAreaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -592,7 +564,7 @@ public static bool TryParseUnit(string str, out ReciprocalAreaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ReciprocalAreaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -672,20 +644,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Recip return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ReciprocalArea left, ReciprocalArea right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ReciprocalArea left, ReciprocalArea right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -701,23 +659,6 @@ public int CompareTo(ReciprocalArea other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReciprocalArea objReciprocalArea)) - return false; - - return Equals(objReciprocalArea); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ReciprocalArea other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ReciprocalArea within the given absolute or relative tolerance. @@ -763,7 +704,7 @@ public bool Equals(ReciprocalArea other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -789,10 +730,9 @@ public override int GetHashCode() public double As(ReciprocalAreaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -813,10 +753,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ReciprocalAreaUnit unitAsReciprocalAreaUnit)) + if (!(unit is ReciprocalAreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); - return As(unitAsReciprocalAreaUnit); + return (double)As(typedUnit); } /// @@ -909,10 +849,10 @@ private bool TryToUnit(ReciprocalAreaUnit unit, out ReciprocalArea? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReciprocalAreaUnit unitAsReciprocalAreaUnit)) + 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(unitAsReciprocalAreaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -956,63 +896,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1094,8 +1000,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ReciprocalAreaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ReciprocalArea.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ReciprocalArea.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs index 2c28b4ebbe..6c6426d6e1 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Reciprocal_length /// [DataContract] - public readonly partial struct ReciprocalLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ReciprocalLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ReciprocalLength() { BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 0, 0, 0); BaseUnit = ReciprocalLengthUnit.InverseMeter; - MaxValue = new ReciprocalLength(double.MaxValue, BaseUnit); - MinValue = new ReciprocalLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.ReciprocalLength; - Units = Enum.GetValues(typeof(ReciprocalLengthUnit)).Cast().Except(new ReciprocalLengthUnit[]{ ReciprocalLengthUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ReciprocalLengthUnit)).Cast().ToArray(); Zero = new ReciprocalLength(0, BaseUnit); Info = new QuantityInfo("ReciprocalLength", new UnitInfo[] @@ -76,7 +72,7 @@ static ReciprocalLength() new UnitInfo(ReciprocalLengthUnit.InverseUsSurveyFoot, "InverseUsSurveyFeet", BaseUnits.Undefined), new UnitInfo(ReciprocalLengthUnit.InverseYard, "InverseYards", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ReciprocalLength); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -90,9 +86,6 @@ static ReciprocalLength() /// If value is NaN or Infinity. public ReciprocalLength(double value, ReciprocalLengthUnit unit) { - if (unit == ReciprocalLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -136,24 +129,6 @@ public ReciprocalLength(double value, UnitSystem unitSystem) /// public static ReciprocalLengthUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ReciprocalLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReciprocalLength MaxValue { get; } - - /// - /// Represents the smallest possible value of ReciprocalLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ReciprocalLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ReciprocalLength quantity. /// @@ -173,6 +148,9 @@ public ReciprocalLength(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -184,12 +162,6 @@ public ReciprocalLength(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ReciprocalLength; - /// /// The of this quantity. /// @@ -314,7 +286,7 @@ public static string GetAbbreviation(ReciprocalLengthUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ReciprocalLengthUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -488,7 +460,7 @@ public static ReciprocalLength Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ReciprocalLength Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -519,7 +491,7 @@ public static bool TryParse(string? str, out ReciprocalLength result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ReciprocalLength result) { return QuantityParser.Default.TryParse( @@ -547,7 +519,7 @@ public static ReciprocalLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -573,7 +545,7 @@ public static bool TryParseUnit(string str, out ReciprocalLengthUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ReciprocalLengthUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -653,20 +625,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Recip return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ReciprocalLength left, ReciprocalLength right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ReciprocalLength left, ReciprocalLength right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -682,23 +640,6 @@ public int CompareTo(ReciprocalLength other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ReciprocalLength objReciprocalLength)) - return false; - - return Equals(objReciprocalLength); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ReciprocalLength other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ReciprocalLength within the given absolute or relative tolerance. @@ -744,7 +685,7 @@ public bool Equals(ReciprocalLength other, double tolerance, ComparisonType comp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -770,10 +711,9 @@ public override int GetHashCode() public double As(ReciprocalLengthUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -794,10 +734,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ReciprocalLengthUnit unitAsReciprocalLengthUnit)) + if (!(unit is ReciprocalLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); - return As(unitAsReciprocalLengthUnit); + return (double)As(typedUnit); } /// @@ -888,10 +828,10 @@ private bool TryToUnit(ReciprocalLengthUnit unit, out ReciprocalLength? converte /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ReciprocalLengthUnit unitAsReciprocalLengthUnit)) + 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(unitAsReciprocalLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -935,63 +875,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1073,8 +979,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ReciprocalLengthUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ReciprocalLength.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ReciprocalLength.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs index d578ae778b..ca9ebe4f6c 100644 --- a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// 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. /// [DataContract] - public readonly partial struct RelativeHumidity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct RelativeHumidity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,17 +53,14 @@ static RelativeHumidity() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = RelativeHumidityUnit.Percent; - MaxValue = new RelativeHumidity(double.MaxValue, BaseUnit); - MinValue = new RelativeHumidity(double.MinValue, BaseUnit); - QuantityType = QuantityType.RelativeHumidity; - Units = Enum.GetValues(typeof(RelativeHumidityUnit)).Cast().Except(new RelativeHumidityUnit[]{ RelativeHumidityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RelativeHumidityUnit)).Cast().ToArray(); Zero = new RelativeHumidity(0, BaseUnit); Info = new QuantityInfo("RelativeHumidity", new UnitInfo[] { new UnitInfo(RelativeHumidityUnit.Percent, "Percent", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.RelativeHumidity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -78,9 +74,6 @@ static RelativeHumidity() /// If value is NaN or Infinity. public RelativeHumidity(double value, RelativeHumidityUnit unit) { - if (unit == RelativeHumidityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -124,24 +117,6 @@ public RelativeHumidity(double value, UnitSystem unitSystem) /// public static RelativeHumidityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of RelativeHumidity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RelativeHumidity MaxValue { get; } - - /// - /// Represents the smallest possible value of RelativeHumidity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RelativeHumidity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the RelativeHumidity quantity. /// @@ -161,6 +136,9 @@ public RelativeHumidity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -172,12 +150,6 @@ public RelativeHumidity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.RelativeHumidity; - /// /// The of this quantity. /// @@ -230,7 +202,7 @@ public static string GetAbbreviation(RelativeHumidityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RelativeHumidityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -314,7 +286,7 @@ public static RelativeHumidity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static RelativeHumidity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -345,7 +317,7 @@ public static bool TryParse(string? str, out RelativeHumidity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out RelativeHumidity result) { return QuantityParser.Default.TryParse( @@ -373,7 +345,7 @@ public static RelativeHumidityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -399,7 +371,7 @@ public static bool TryParseUnit(string str, out RelativeHumidityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RelativeHumidityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -479,20 +451,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Relat return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(RelativeHumidity left, RelativeHumidity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(RelativeHumidity left, RelativeHumidity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -508,23 +466,6 @@ public int CompareTo(RelativeHumidity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is RelativeHumidity objRelativeHumidity)) - return false; - - return Equals(objRelativeHumidity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(RelativeHumidity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another RelativeHumidity within the given absolute or relative tolerance. @@ -570,7 +511,7 @@ public bool Equals(RelativeHumidity other, double tolerance, ComparisonType comp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -596,10 +537,9 @@ public override int GetHashCode() public double As(RelativeHumidityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -620,10 +560,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RelativeHumidityUnit unitAsRelativeHumidityUnit)) + if (!(unit is RelativeHumidityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); - return As(unitAsRelativeHumidityUnit); + return (double)As(typedUnit); } /// @@ -696,10 +636,10 @@ private bool TryToUnit(RelativeHumidityUnit unit, out RelativeHumidity? converte /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RelativeHumidityUnit unitAsRelativeHumidityUnit)) + 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(unitAsRelativeHumidityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -743,63 +683,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -881,8 +787,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RelativeHumidityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return RelativeHumidity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return RelativeHumidity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index d43cd4251b..d637aa381a 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Angular acceleration is the rate of change of rotational speed. /// [DataContract] - public readonly partial struct RotationalAcceleration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct RotationalAcceleration : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static RotationalAcceleration() { BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); BaseUnit = RotationalAccelerationUnit.RadianPerSecondSquared; - MaxValue = new RotationalAcceleration(double.MaxValue, BaseUnit); - MinValue = new RotationalAcceleration(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalAcceleration; - Units = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().Except(new RotationalAccelerationUnit[]{ RotationalAccelerationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().ToArray(); Zero = new RotationalAcceleration(0, BaseUnit); Info = new QuantityInfo("RotationalAcceleration", new UnitInfo[] @@ -67,7 +63,7 @@ static RotationalAcceleration() new UnitInfo(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, "RevolutionsPerMinutePerSecond", BaseUnits.Undefined), new UnitInfo(RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionsPerSecondSquared", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.RotationalAcceleration); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static RotationalAcceleration() /// If value is NaN or Infinity. public RotationalAcceleration(double value, RotationalAccelerationUnit unit) { - if (unit == RotationalAccelerationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) /// public static RotationalAccelerationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of RotationalAcceleration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalAcceleration MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalAcceleration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalAcceleration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the RotationalAcceleration quantity. /// @@ -164,6 +139,9 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.RotationalAcceleration; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RotationalAccelerationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static RotationalAcceleration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static RotationalAcceleration Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out RotationalAcceleration result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out RotationalAcceleration result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static RotationalAccelerationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalAccelerationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -536,20 +508,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -565,23 +523,6 @@ public int CompareTo(RotationalAcceleration other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalAcceleration objRotationalAcceleration)) - return false; - - return Equals(objRotationalAcceleration); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(RotationalAcceleration other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another RotationalAcceleration within the given absolute or relative tolerance. @@ -627,7 +568,7 @@ public bool Equals(RotationalAcceleration other, double tolerance, ComparisonTyp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -653,10 +594,9 @@ public override int GetHashCode() public double As(RotationalAccelerationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -677,10 +617,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RotationalAccelerationUnit unitAsRotationalAccelerationUnit)) + if (!(unit is RotationalAccelerationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalAccelerationUnit); + return (double)As(typedUnit); } /// @@ -759,10 +699,10 @@ private bool TryToUnit(RotationalAccelerationUnit unit, out RotationalAccelerati /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalAccelerationUnit unitAsRotationalAccelerationUnit)) + 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(unitAsRotationalAccelerationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -806,63 +746,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -944,8 +850,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RotationalAccelerationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return RotationalAcceleration.QuantityType; else if (conversionType == typeof(QuantityInfo)) return RotationalAcceleration.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index 1ff1a2b8e1..8bcdcd2c67 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter "omega"). /// [DataContract] - public readonly partial struct RotationalSpeed : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct RotationalSpeed : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static RotationalSpeed() { BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); BaseUnit = RotationalSpeedUnit.RadianPerSecond; - MaxValue = new RotationalSpeed(double.MaxValue, BaseUnit); - MinValue = new RotationalSpeed(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalSpeed; - Units = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().Except(new RotationalSpeedUnit[]{ RotationalSpeedUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().ToArray(); Zero = new RotationalSpeed(0, BaseUnit); Info = new QuantityInfo("RotationalSpeed", new UnitInfo[] @@ -76,7 +72,7 @@ static RotationalSpeed() new UnitInfo(RotationalSpeedUnit.RevolutionPerMinute, "RevolutionsPerMinute", BaseUnits.Undefined), new UnitInfo(RotationalSpeedUnit.RevolutionPerSecond, "RevolutionsPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.RotationalSpeed); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -90,9 +86,6 @@ static RotationalSpeed() /// If value is NaN or Infinity. public RotationalSpeed(double value, RotationalSpeedUnit unit) { - if (unit == RotationalSpeedUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -136,24 +129,6 @@ public RotationalSpeed(double value, UnitSystem unitSystem) /// public static RotationalSpeedUnit BaseUnit { get; } - /// - /// Represents the largest possible value of RotationalSpeed - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalSpeed MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalSpeed - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalSpeed MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the RotationalSpeed quantity. /// @@ -173,6 +148,9 @@ public RotationalSpeed(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -184,12 +162,6 @@ public RotationalSpeed(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.RotationalSpeed; - /// /// The of this quantity. /// @@ -350,7 +322,7 @@ public static string GetAbbreviation(RotationalSpeedUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RotationalSpeedUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -554,7 +526,7 @@ public static RotationalSpeed Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static RotationalSpeed Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -585,7 +557,7 @@ public static bool TryParse(string? str, out RotationalSpeed result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out RotationalSpeed result) { return QuantityParser.Default.TryParse( @@ -613,7 +585,7 @@ public static RotationalSpeedUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -639,7 +611,7 @@ public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalSpeedUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -719,20 +691,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(RotationalSpeed left, RotationalSpeed right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(RotationalSpeed left, RotationalSpeed right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -748,23 +706,6 @@ public int CompareTo(RotationalSpeed other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalSpeed objRotationalSpeed)) - return false; - - return Equals(objRotationalSpeed); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(RotationalSpeed other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another RotationalSpeed within the given absolute or relative tolerance. @@ -810,7 +751,7 @@ public bool Equals(RotationalSpeed other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -836,10 +777,9 @@ public override int GetHashCode() public double As(RotationalSpeedUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -860,10 +800,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RotationalSpeedUnit unitAsRotationalSpeedUnit)) + if (!(unit is RotationalSpeedUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalSpeedUnit); + return (double)As(typedUnit); } /// @@ -960,10 +900,10 @@ private bool TryToUnit(RotationalSpeedUnit unit, out RotationalSpeed? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalSpeedUnit unitAsRotationalSpeedUnit)) + 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(unitAsRotationalSpeedUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1007,63 +947,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1145,8 +1051,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RotationalSpeedUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return RotationalSpeed.QuantityType; else if (conversionType == typeof(QuantityInfo)) return RotationalSpeed.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs index c672e21a04..2885b7a89c 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// [DataContract] - public readonly partial struct RotationalStiffness : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct RotationalStiffness : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static RotationalStiffness() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); BaseUnit = RotationalStiffnessUnit.NewtonMeterPerRadian; - MaxValue = new RotationalStiffness(double.MaxValue, BaseUnit); - MinValue = new RotationalStiffness(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalStiffness; - Units = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().Except(new RotationalStiffnessUnit[]{ RotationalStiffnessUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().ToArray(); Zero = new RotationalStiffness(0, BaseUnit); Info = new QuantityInfo("RotationalStiffness", new UnitInfo[] @@ -96,7 +92,7 @@ static RotationalStiffness() new UnitInfo(RotationalStiffnessUnit.PoundForceFeetPerRadian, "PoundForceFeetPerRadian", BaseUnits.Undefined), new UnitInfo(RotationalStiffnessUnit.PoundForceFootPerDegrees, "PoundForceFeetPerDegrees", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.RotationalStiffness); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -110,9 +106,6 @@ static RotationalStiffness() /// If value is NaN or Infinity. public RotationalStiffness(double value, RotationalStiffnessUnit unit) { - if (unit == RotationalStiffnessUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -156,24 +149,6 @@ public RotationalStiffness(double value, UnitSystem unitSystem) /// public static RotationalStiffnessUnit BaseUnit { get; } - /// - /// Represents the largest possible value of RotationalStiffness - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalStiffness MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalStiffness - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalStiffness MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the RotationalStiffness quantity. /// @@ -193,6 +168,9 @@ public RotationalStiffness(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -204,12 +182,6 @@ public RotationalStiffness(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.RotationalStiffness; - /// /// The of this quantity. /// @@ -518,7 +490,7 @@ public static string GetAbbreviation(RotationalStiffnessUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RotationalStiffnessUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -922,7 +894,7 @@ public static RotationalStiffness Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static RotationalStiffness Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -953,7 +925,7 @@ public static bool TryParse(string? str, out RotationalStiffness result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out RotationalStiffness result) { return QuantityParser.Default.TryParse( @@ -981,7 +953,7 @@ public static RotationalStiffnessUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1007,7 +979,7 @@ public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalStiffnessUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1087,20 +1059,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(RotationalStiffness left, RotationalStiffness right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(RotationalStiffness left, RotationalStiffness right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1116,23 +1074,6 @@ public int CompareTo(RotationalStiffness other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalStiffness objRotationalStiffness)) - return false; - - return Equals(objRotationalStiffness); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(RotationalStiffness other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another RotationalStiffness within the given absolute or relative tolerance. @@ -1178,7 +1119,7 @@ public bool Equals(RotationalStiffness other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1204,10 +1145,9 @@ public override int GetHashCode() public double As(RotationalStiffnessUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1228,10 +1168,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RotationalStiffnessUnit unitAsRotationalStiffnessUnit)) + if (!(unit is RotationalStiffnessUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalStiffnessUnit); + return (double)As(typedUnit); } /// @@ -1368,10 +1308,10 @@ private bool TryToUnit(RotationalStiffnessUnit unit, out RotationalStiffness? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalStiffnessUnit unitAsRotationalStiffnessUnit)) + 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(unitAsRotationalStiffnessUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1415,63 +1355,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1553,8 +1459,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RotationalStiffnessUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return RotationalStiffness.QuantityType; else if (conversionType == typeof(QuantityInfo)) return RotationalStiffness.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index 03c575e038..9f97e88234 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// [DataContract] - public readonly partial struct RotationalStiffnessPerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct RotationalStiffnessPerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static RotationalStiffnessPerLength() { BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); BaseUnit = RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; - MaxValue = new RotationalStiffnessPerLength(double.MaxValue, BaseUnit); - MinValue = new RotationalStiffnessPerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.RotationalStiffnessPerLength; - Units = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().Except(new RotationalStiffnessPerLengthUnit[]{ RotationalStiffnessPerLengthUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().ToArray(); Zero = new RotationalStiffnessPerLength(0, BaseUnit); Info = new QuantityInfo("RotationalStiffnessPerLength", new UnitInfo[] @@ -68,7 +64,7 @@ static RotationalStiffnessPerLength() new UnitInfo(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, "NewtonMetersPerRadianPerMeter", BaseUnits.Undefined), new UnitInfo(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "PoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.RotationalStiffnessPerLength); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -82,9 +78,6 @@ static RotationalStiffnessPerLength() /// If value is NaN or Infinity. public RotationalStiffnessPerLength(double value, RotationalStiffnessPerLengthUnit unit) { - if (unit == RotationalStiffnessPerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -128,24 +121,6 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) /// public static RotationalStiffnessPerLengthUnit BaseUnit { get; } - /// - /// Represents the largest possible value of RotationalStiffnessPerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalStiffnessPerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of RotationalStiffnessPerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static RotationalStiffnessPerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the RotationalStiffnessPerLength quantity. /// @@ -165,6 +140,9 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -176,12 +154,6 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.RotationalStiffnessPerLength; - /// /// The of this quantity. /// @@ -266,7 +238,7 @@ public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -390,7 +362,7 @@ public static RotationalStiffnessPerLength Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static RotationalStiffnessPerLength Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -421,7 +393,7 @@ public static bool TryParse(string? str, out RotationalStiffnessPerLength result /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out RotationalStiffnessPerLength result) { return QuantityParser.Default.TryParse( @@ -449,7 +421,7 @@ public static RotationalStiffnessPerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -475,7 +447,7 @@ public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalStiffnessPerLengthUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -555,20 +527,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Rotat return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -584,23 +542,6 @@ public int CompareTo(RotationalStiffnessPerLength other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is RotationalStiffnessPerLength objRotationalStiffnessPerLength)) - return false; - - return Equals(objRotationalStiffnessPerLength); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(RotationalStiffnessPerLength other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another RotationalStiffnessPerLength within the given absolute or relative tolerance. @@ -646,7 +587,7 @@ public bool Equals(RotationalStiffnessPerLength other, double tolerance, Compari if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -672,10 +613,9 @@ public override int GetHashCode() public double As(RotationalStiffnessPerLengthUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -696,10 +636,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is RotationalStiffnessPerLengthUnit unitAsRotationalStiffnessPerLengthUnit)) + if (!(unit is RotationalStiffnessPerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsRotationalStiffnessPerLengthUnit); + return (double)As(typedUnit); } /// @@ -780,10 +720,10 @@ private bool TryToUnit(RotationalStiffnessPerLengthUnit unit, out RotationalStif /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is RotationalStiffnessPerLengthUnit unitAsRotationalStiffnessPerLengthUnit)) + 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(unitAsRotationalStiffnessPerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -827,63 +767,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -965,8 +871,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(RotationalStiffnessPerLengthUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return RotationalStiffnessPerLength.QuantityType; else if (conversionType == typeof(QuantityInfo)) return RotationalStiffnessPerLength.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs index 1ce91f3b84..270d576ad2 100644 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A way of representing a number of items. /// [DataContract] - public readonly partial struct Scalar : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Scalar : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,17 +53,14 @@ static Scalar() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = ScalarUnit.Amount; - MaxValue = new Scalar(double.MaxValue, BaseUnit); - MinValue = new Scalar(double.MinValue, BaseUnit); - QuantityType = QuantityType.Scalar; - Units = Enum.GetValues(typeof(ScalarUnit)).Cast().Except(new ScalarUnit[]{ ScalarUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ScalarUnit)).Cast().ToArray(); Zero = new Scalar(0, BaseUnit); Info = new QuantityInfo("Scalar", new UnitInfo[] { new UnitInfo(ScalarUnit.Amount, "Amount", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Scalar); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -78,9 +74,6 @@ static Scalar() /// If value is NaN or Infinity. public Scalar(double value, ScalarUnit unit) { - if (unit == ScalarUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -124,24 +117,6 @@ public Scalar(double value, UnitSystem unitSystem) /// public static ScalarUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Scalar - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Scalar MaxValue { get; } - - /// - /// Represents the smallest possible value of Scalar - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Scalar MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Scalar quantity. /// @@ -161,6 +136,9 @@ public Scalar(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -172,12 +150,6 @@ public Scalar(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Scalar; - /// /// The of this quantity. /// @@ -230,7 +202,7 @@ public static string GetAbbreviation(ScalarUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ScalarUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -314,7 +286,7 @@ public static Scalar Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Scalar Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -345,7 +317,7 @@ public static bool TryParse(string? str, out Scalar result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Scalar result) { return QuantityParser.Default.TryParse( @@ -373,7 +345,7 @@ public static ScalarUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -399,7 +371,7 @@ public static bool TryParseUnit(string str, out ScalarUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ScalarUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -479,20 +451,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Scala return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Scalar left, Scalar right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Scalar left, Scalar right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -508,23 +466,6 @@ public int CompareTo(Scalar other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Scalar objScalar)) - return false; - - return Equals(objScalar); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Scalar other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Scalar within the given absolute or relative tolerance. @@ -570,7 +511,7 @@ 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 = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -596,10 +537,9 @@ public override int GetHashCode() public double As(ScalarUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -620,10 +560,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ScalarUnit unitAsScalarUnit)) + if (!(unit is ScalarUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - return As(unitAsScalarUnit); + return (double)As(typedUnit); } /// @@ -696,10 +636,10 @@ private bool TryToUnit(ScalarUnit unit, out Scalar? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ScalarUnit unitAsScalarUnit)) + 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(unitAsScalarUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -743,63 +683,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -881,8 +787,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ScalarUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Scalar.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Scalar.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index 9cc77bec44..59997371ea 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Solid_angle /// [DataContract] - public readonly partial struct SolidAngle : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct SolidAngle : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static SolidAngle() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = SolidAngleUnit.Steradian; - MaxValue = new SolidAngle(double.MaxValue, BaseUnit); - MinValue = new SolidAngle(double.MinValue, BaseUnit); - QuantityType = QuantityType.SolidAngle; - Units = Enum.GetValues(typeof(SolidAngleUnit)).Cast().Except(new SolidAngleUnit[]{ SolidAngleUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SolidAngleUnit)).Cast().ToArray(); Zero = new SolidAngle(0, BaseUnit); Info = new QuantityInfo("SolidAngle", new UnitInfo[] { new UnitInfo(SolidAngleUnit.Steradian, "Steradians", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.SolidAngle); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static SolidAngle() /// If value is NaN or Infinity. public SolidAngle(double value, SolidAngleUnit unit) { - if (unit == SolidAngleUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public SolidAngle(double value, UnitSystem unitSystem) /// public static SolidAngleUnit BaseUnit { get; } - /// - /// Represents the largest possible value of SolidAngle - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SolidAngle MaxValue { get; } - - /// - /// Represents the smallest possible value of SolidAngle - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SolidAngle MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the SolidAngle quantity. /// @@ -164,6 +139,9 @@ public SolidAngle(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public SolidAngle(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.SolidAngle; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(SolidAngleUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SolidAngleUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static SolidAngle Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static SolidAngle Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out SolidAngle result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out SolidAngle result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static SolidAngleUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out SolidAngleUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SolidAngleUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Solid return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(SolidAngle left, SolidAngle right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(SolidAngle left, SolidAngle right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(SolidAngle other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is SolidAngle objSolidAngle)) - return false; - - return Equals(objSolidAngle); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(SolidAngle other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another SolidAngle within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(SolidAngle other, double tolerance, ComparisonType comparison if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(SolidAngleUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SolidAngleUnit unitAsSolidAngleUnit)) + if (!(unit is SolidAngleUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); - return As(unitAsSolidAngleUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(SolidAngleUnit unit, out SolidAngle? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SolidAngleUnit unitAsSolidAngleUnit)) + 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(unitAsSolidAngleUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SolidAngleUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return SolidAngle.QuantityType; else if (conversionType == typeof(QuantityInfo)) return SolidAngle.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index 3d3d3769b9..7f4e83de44 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Specific_energy /// [DataContract] - public readonly partial struct SpecificEnergy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct SpecificEnergy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static SpecificEnergy() { BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); BaseUnit = SpecificEnergyUnit.JoulePerKilogram; - MaxValue = new SpecificEnergy(double.MaxValue, BaseUnit); - MinValue = new SpecificEnergy(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificEnergy; - Units = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().Except(new SpecificEnergyUnit[]{ SpecificEnergyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().ToArray(); Zero = new SpecificEnergy(0, BaseUnit); Info = new QuantityInfo("SpecificEnergy", new UnitInfo[] @@ -95,7 +91,7 @@ static SpecificEnergy() new UnitInfo(SpecificEnergyUnit.WattHourPerKilogram, "WattHoursPerKilogram", BaseUnits.Undefined), new UnitInfo(SpecificEnergyUnit.WattHourPerPound, "WattHoursPerPound", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.SpecificEnergy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -109,9 +105,6 @@ static SpecificEnergy() /// If value is NaN or Infinity. public SpecificEnergy(double value, SpecificEnergyUnit unit) { - if (unit == SpecificEnergyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -155,24 +148,6 @@ public SpecificEnergy(double value, UnitSystem unitSystem) /// public static SpecificEnergyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of SpecificEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificEnergy MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificEnergy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificEnergy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the SpecificEnergy quantity. /// @@ -192,6 +167,9 @@ public SpecificEnergy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -203,12 +181,6 @@ public SpecificEnergy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.SpecificEnergy; - /// /// The of this quantity. /// @@ -485,7 +457,7 @@ public static string GetAbbreviation(SpecificEnergyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SpecificEnergyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -849,7 +821,7 @@ public static SpecificEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static SpecificEnergy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -880,7 +852,7 @@ public static bool TryParse(string? str, out SpecificEnergy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out SpecificEnergy result) { return QuantityParser.Default.TryParse( @@ -908,7 +880,7 @@ public static SpecificEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -934,7 +906,7 @@ public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificEnergyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1014,20 +986,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(SpecificEnergy left, SpecificEnergy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(SpecificEnergy left, SpecificEnergy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1043,23 +1001,6 @@ public int CompareTo(SpecificEnergy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificEnergy objSpecificEnergy)) - return false; - - return Equals(objSpecificEnergy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(SpecificEnergy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another SpecificEnergy within the given absolute or relative tolerance. @@ -1105,7 +1046,7 @@ public bool Equals(SpecificEnergy other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1131,10 +1072,9 @@ public override int GetHashCode() public double As(SpecificEnergyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1155,10 +1095,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SpecificEnergyUnit unitAsSpecificEnergyUnit)) + if (!(unit is SpecificEnergyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificEnergyUnit); + return (double)As(typedUnit); } /// @@ -1287,10 +1227,10 @@ private bool TryToUnit(SpecificEnergyUnit unit, out SpecificEnergy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificEnergyUnit unitAsSpecificEnergyUnit)) + 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(unitAsSpecificEnergyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1334,63 +1274,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1472,8 +1378,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SpecificEnergyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return SpecificEnergy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return SpecificEnergy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index 6b7a8e1420..5cb253e90c 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. /// [DataContract] - public readonly partial struct SpecificEntropy : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct SpecificEntropy : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static SpecificEntropy() { BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); BaseUnit = SpecificEntropyUnit.JoulePerKilogramKelvin; - MaxValue = new SpecificEntropy(double.MaxValue, BaseUnit); - MinValue = new SpecificEntropy(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificEntropy; - Units = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().Except(new SpecificEntropyUnit[]{ SpecificEntropyUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().ToArray(); Zero = new SpecificEntropy(0, BaseUnit); Info = new QuantityInfo("SpecificEntropy", new UnitInfo[] @@ -72,7 +68,7 @@ static SpecificEntropy() new UnitInfo(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, "MegajoulesPerKilogramDegreeCelsius", BaseUnits.Undefined), new UnitInfo(SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MegajoulesPerKilogramKelvin", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.SpecificEntropy); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -86,9 +82,6 @@ static SpecificEntropy() /// If value is NaN or Infinity. public SpecificEntropy(double value, SpecificEntropyUnit unit) { - if (unit == SpecificEntropyUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -132,24 +125,6 @@ public SpecificEntropy(double value, UnitSystem unitSystem) /// public static SpecificEntropyUnit BaseUnit { get; } - /// - /// Represents the largest possible value of SpecificEntropy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificEntropy MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificEntropy - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificEntropy MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the SpecificEntropy quantity. /// @@ -169,6 +144,9 @@ public SpecificEntropy(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -180,12 +158,6 @@ public SpecificEntropy(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.SpecificEntropy; - /// /// The of this quantity. /// @@ -302,7 +274,7 @@ public static string GetAbbreviation(SpecificEntropyUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SpecificEntropyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -466,7 +438,7 @@ public static SpecificEntropy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static SpecificEntropy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -497,7 +469,7 @@ public static bool TryParse(string? str, out SpecificEntropy result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out SpecificEntropy result) { return QuantityParser.Default.TryParse( @@ -525,7 +497,7 @@ public static SpecificEntropyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -551,7 +523,7 @@ public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificEntropyUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -631,20 +603,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(SpecificEntropy left, SpecificEntropy right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(SpecificEntropy left, SpecificEntropy right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -660,23 +618,6 @@ public int CompareTo(SpecificEntropy other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificEntropy objSpecificEntropy)) - return false; - - return Equals(objSpecificEntropy); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(SpecificEntropy other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another SpecificEntropy within the given absolute or relative tolerance. @@ -722,7 +663,7 @@ public bool Equals(SpecificEntropy other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -748,10 +689,9 @@ public override int GetHashCode() public double As(SpecificEntropyUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -772,10 +712,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SpecificEntropyUnit unitAsSpecificEntropyUnit)) + if (!(unit is SpecificEntropyUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificEntropyUnit); + return (double)As(typedUnit); } /// @@ -864,10 +804,10 @@ private bool TryToUnit(SpecificEntropyUnit unit, out SpecificEntropy? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificEntropyUnit unitAsSpecificEntropyUnit)) + 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(unitAsSpecificEntropyUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -911,63 +851,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1049,8 +955,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SpecificEntropyUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return SpecificEntropy.QuantityType; else if (conversionType == typeof(QuantityInfo)) return SpecificEntropy.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index 55af59cdaa..4ed93c01cc 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Thrust-specific_fuel_consumption /// [DataContract] - public readonly partial struct SpecificFuelConsumption : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct SpecificFuelConsumption : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static SpecificFuelConsumption() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond; - MaxValue = new SpecificFuelConsumption(double.MaxValue, BaseUnit); - MinValue = new SpecificFuelConsumption(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificFuelConsumption; - Units = Enum.GetValues(typeof(SpecificFuelConsumptionUnit)).Cast().Except(new SpecificFuelConsumptionUnit[]{ SpecificFuelConsumptionUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SpecificFuelConsumptionUnit)).Cast().ToArray(); Zero = new SpecificFuelConsumption(0, BaseUnit); Info = new QuantityInfo("SpecificFuelConsumption", new UnitInfo[] @@ -70,7 +66,7 @@ static SpecificFuelConsumption() new UnitInfo(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, "KilogramsPerKiloNewtonSecond", BaseUnits.Undefined), new UnitInfo(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "PoundsMassPerPoundForceHour", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.SpecificFuelConsumption); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static SpecificFuelConsumption() /// If value is NaN or Infinity. public SpecificFuelConsumption(double value, SpecificFuelConsumptionUnit unit) { - if (unit == SpecificFuelConsumptionUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) /// public static SpecificFuelConsumptionUnit BaseUnit { get; } - /// - /// Represents the largest possible value of SpecificFuelConsumption - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificFuelConsumption MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificFuelConsumption - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificFuelConsumption MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the SpecificFuelConsumption quantity. /// @@ -167,6 +142,9 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.SpecificFuelConsumption; - /// /// The of this quantity. /// @@ -239,9 +211,9 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) 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.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)"}); } @@ -260,7 +232,7 @@ public static string GetAbbreviation(SpecificFuelConsumptionUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SpecificFuelConsumptionUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -374,7 +346,7 @@ public static SpecificFuelConsumption Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static SpecificFuelConsumption Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -405,7 +377,7 @@ public static bool TryParse(string? str, out SpecificFuelConsumption result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out SpecificFuelConsumption result) { return QuantityParser.Default.TryParse( @@ -433,7 +405,7 @@ public static SpecificFuelConsumptionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -459,7 +431,7 @@ public static bool TryParseUnit(string str, out SpecificFuelConsumptionUnit unit /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificFuelConsumptionUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -539,20 +511,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(SpecificFuelConsumption left, SpecificFuelConsumption right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(SpecificFuelConsumption left, SpecificFuelConsumption right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -568,23 +526,6 @@ public int CompareTo(SpecificFuelConsumption other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificFuelConsumption objSpecificFuelConsumption)) - return false; - - return Equals(objSpecificFuelConsumption); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(SpecificFuelConsumption other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another SpecificFuelConsumption within the given absolute or relative tolerance. @@ -630,7 +571,7 @@ public bool Equals(SpecificFuelConsumption other, double tolerance, ComparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -656,10 +597,9 @@ public override int GetHashCode() public double As(SpecificFuelConsumptionUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -680,10 +620,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SpecificFuelConsumptionUnit unitAsSpecificFuelConsumptionUnit)) + if (!(unit is SpecificFuelConsumptionUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificFuelConsumptionUnit); + return (double)As(typedUnit); } /// @@ -762,10 +702,10 @@ private bool TryToUnit(SpecificFuelConsumptionUnit unit, out SpecificFuelConsump /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificFuelConsumptionUnit unitAsSpecificFuelConsumptionUnit)) + 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(unitAsSpecificFuelConsumptionUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -809,63 +749,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -947,8 +853,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SpecificFuelConsumptionUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return SpecificFuelConsumption.QuantityType; else if (conversionType == typeof(QuantityInfo)) return SpecificFuelConsumption.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index 1961fcc327..e901f6a002 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well. /// [DataContract] - public readonly partial struct SpecificVolume : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct SpecificVolume : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static SpecificVolume() { BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); BaseUnit = SpecificVolumeUnit.CubicMeterPerKilogram; - MaxValue = new SpecificVolume(double.MaxValue, BaseUnit); - MinValue = new SpecificVolume(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificVolume; - Units = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().Except(new SpecificVolumeUnit[]{ SpecificVolumeUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().ToArray(); Zero = new SpecificVolume(0, BaseUnit); Info = new QuantityInfo("SpecificVolume", new UnitInfo[] @@ -66,7 +62,7 @@ static SpecificVolume() new UnitInfo(SpecificVolumeUnit.CubicMeterPerKilogram, "CubicMetersPerKilogram", BaseUnits.Undefined), new UnitInfo(SpecificVolumeUnit.MillicubicMeterPerKilogram, "MillicubicMetersPerKilogram", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.SpecificVolume); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -80,9 +76,6 @@ static SpecificVolume() /// If value is NaN or Infinity. public SpecificVolume(double value, SpecificVolumeUnit unit) { - if (unit == SpecificVolumeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -126,24 +119,6 @@ public SpecificVolume(double value, UnitSystem unitSystem) /// public static SpecificVolumeUnit BaseUnit { get; } - /// - /// Represents the largest possible value of SpecificVolume - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificVolume MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificVolume - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificVolume MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the SpecificVolume quantity. /// @@ -163,6 +138,9 @@ public SpecificVolume(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -174,12 +152,6 @@ public SpecificVolume(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.SpecificVolume; - /// /// The of this quantity. /// @@ -248,7 +220,7 @@ public static string GetAbbreviation(SpecificVolumeUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SpecificVolumeUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -352,7 +324,7 @@ public static SpecificVolume Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static SpecificVolume Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -383,7 +355,7 @@ public static bool TryParse(string? str, out SpecificVolume result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out SpecificVolume result) { return QuantityParser.Default.TryParse( @@ -411,7 +383,7 @@ public static SpecificVolumeUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -437,7 +409,7 @@ public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificVolumeUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -517,20 +489,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(SpecificVolume left, SpecificVolume right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(SpecificVolume left, SpecificVolume right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -546,23 +504,6 @@ public int CompareTo(SpecificVolume other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificVolume objSpecificVolume)) - return false; - - return Equals(objSpecificVolume); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(SpecificVolume other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another SpecificVolume within the given absolute or relative tolerance. @@ -608,7 +549,7 @@ public bool Equals(SpecificVolume other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -634,10 +575,9 @@ public override int GetHashCode() public double As(SpecificVolumeUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -658,10 +598,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SpecificVolumeUnit unitAsSpecificVolumeUnit)) + if (!(unit is SpecificVolumeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificVolumeUnit); + return (double)As(typedUnit); } /// @@ -738,10 +678,10 @@ private bool TryToUnit(SpecificVolumeUnit unit, out SpecificVolume? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificVolumeUnit unitAsSpecificVolumeUnit)) + 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(unitAsSpecificVolumeUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -785,63 +725,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -923,8 +829,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SpecificVolumeUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return SpecificVolume.QuantityType; else if (conversionType == typeof(QuantityInfo)) return SpecificVolume.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index 21717c48ed..c2f728eb9b 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Specificweight /// [DataContract] - public readonly partial struct SpecificWeight : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct SpecificWeight : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static SpecificWeight() { BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); BaseUnit = SpecificWeightUnit.NewtonPerCubicMeter; - MaxValue = new SpecificWeight(double.MaxValue, BaseUnit); - MinValue = new SpecificWeight(double.MinValue, BaseUnit); - QuantityType = QuantityType.SpecificWeight; - Units = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().Except(new SpecificWeightUnit[]{ SpecificWeightUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().ToArray(); Zero = new SpecificWeight(0, BaseUnit); Info = new QuantityInfo("SpecificWeight", new UnitInfo[] @@ -83,7 +79,7 @@ static SpecificWeight() new UnitInfo(SpecificWeightUnit.TonneForcePerCubicMeter, "TonnesForcePerCubicMeter", BaseUnits.Undefined), new UnitInfo(SpecificWeightUnit.TonneForcePerCubicMillimeter, "TonnesForcePerCubicMillimeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.SpecificWeight); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -97,9 +93,6 @@ static SpecificWeight() /// If value is NaN or Infinity. public SpecificWeight(double value, SpecificWeightUnit unit) { - if (unit == SpecificWeightUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -143,24 +136,6 @@ public SpecificWeight(double value, UnitSystem unitSystem) /// public static SpecificWeightUnit BaseUnit { get; } - /// - /// Represents the largest possible value of SpecificWeight - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificWeight MaxValue { get; } - - /// - /// Represents the smallest possible value of SpecificWeight - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static SpecificWeight MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the SpecificWeight quantity. /// @@ -180,6 +155,9 @@ public SpecificWeight(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -191,12 +169,6 @@ public SpecificWeight(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.SpecificWeight; - /// /// The of this quantity. /// @@ -377,7 +349,7 @@ public static string GetAbbreviation(SpecificWeightUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SpecificWeightUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -621,7 +593,7 @@ public static SpecificWeight Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static SpecificWeight Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -652,7 +624,7 @@ public static bool TryParse(string? str, out SpecificWeight result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out SpecificWeight result) { return QuantityParser.Default.TryParse( @@ -680,7 +652,7 @@ public static SpecificWeightUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -706,7 +678,7 @@ public static bool TryParseUnit(string str, out SpecificWeightUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificWeightUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -786,20 +758,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speci return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(SpecificWeight left, SpecificWeight right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(SpecificWeight left, SpecificWeight right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -815,23 +773,6 @@ public int CompareTo(SpecificWeight other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is SpecificWeight objSpecificWeight)) - return false; - - return Equals(objSpecificWeight); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(SpecificWeight other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another SpecificWeight within the given absolute or relative tolerance. @@ -877,7 +818,7 @@ public bool Equals(SpecificWeight other, double tolerance, ComparisonType compar if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -903,10 +844,9 @@ public override int GetHashCode() public double As(SpecificWeightUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -927,10 +867,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SpecificWeightUnit unitAsSpecificWeightUnit)) + if (!(unit is SpecificWeightUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); - return As(unitAsSpecificWeightUnit); + return (double)As(typedUnit); } /// @@ -1035,10 +975,10 @@ private bool TryToUnit(SpecificWeightUnit unit, out SpecificWeight? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpecificWeightUnit unitAsSpecificWeightUnit)) + 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(unitAsSpecificWeightUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1082,63 +1022,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1220,8 +1126,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SpecificWeightUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return SpecificWeight.QuantityType; else if (conversionType == typeof(QuantityInfo)) return SpecificWeight.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index 847c8ebb0e..23f1c22189 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero. /// [DataContract] - public readonly partial struct Speed : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Speed : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Speed() { BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); BaseUnit = SpeedUnit.MeterPerSecond; - MaxValue = new Speed(double.MaxValue, BaseUnit); - MinValue = new Speed(double.MinValue, BaseUnit); - QuantityType = QuantityType.Speed; - Units = Enum.GetValues(typeof(SpeedUnit)).Cast().Except(new SpeedUnit[]{ SpeedUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(SpeedUnit)).Cast().ToArray(); Zero = new Speed(0, BaseUnit); Info = new QuantityInfo("Speed", new UnitInfo[] @@ -96,7 +92,7 @@ static Speed() new UnitInfo(SpeedUnit.YardPerMinute, "YardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute)), new UnitInfo(SpeedUnit.YardPerSecond, "YardsPerSecond", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Second)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Speed); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -110,9 +106,6 @@ static Speed() /// If value is NaN or Infinity. public Speed(double value, SpeedUnit unit) { - if (unit == SpeedUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -156,24 +149,6 @@ public Speed(double value, UnitSystem unitSystem) /// public static SpeedUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Speed - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Speed MaxValue { get; } - - /// - /// Represents the smallest possible value of Speed - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Speed MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Speed quantity. /// @@ -193,6 +168,9 @@ public Speed(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -204,12 +182,6 @@ public Speed(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Speed; - /// /// The of this quantity. /// @@ -542,7 +514,7 @@ public static string GetAbbreviation(SpeedUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(SpeedUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -946,7 +918,7 @@ public static Speed Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Speed Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -977,7 +949,7 @@ public static bool TryParse(string? str, out Speed result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Speed result) { return QuantityParser.Default.TryParse( @@ -1005,7 +977,7 @@ public static SpeedUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1031,7 +1003,7 @@ public static bool TryParseUnit(string str, out SpeedUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out SpeedUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1111,20 +1083,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Speed return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Speed left, Speed right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Speed left, Speed right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1140,23 +1098,6 @@ public int CompareTo(Speed other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Speed objSpeed)) - return false; - - return Equals(objSpeed); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Speed other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Speed within the given absolute or relative tolerance. @@ -1202,7 +1143,7 @@ public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1228,10 +1169,9 @@ public override int GetHashCode() public double As(SpeedUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1252,10 +1192,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is SpeedUnit unitAsSpeedUnit)) + if (!(unit is SpeedUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); - return As(unitAsSpeedUnit); + return (double)As(typedUnit); } /// @@ -1392,10 +1332,10 @@ private bool TryToUnit(SpeedUnit unit, out Speed? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is SpeedUnit unitAsSpeedUnit)) + 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(unitAsSpeedUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1439,63 +1379,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1577,8 +1483,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(SpeedUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Speed.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Speed.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index a385e42d9d..8fe6f311ea 100644 --- a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// 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. /// [DataContract] - public readonly partial struct StandardVolumeFlow : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct StandardVolumeFlow : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static StandardVolumeFlow() { BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); BaseUnit = StandardVolumeFlowUnit.StandardCubicMeterPerSecond; - MaxValue = new StandardVolumeFlow(double.MaxValue, BaseUnit); - MinValue = new StandardVolumeFlow(double.MinValue, BaseUnit); - QuantityType = QuantityType.StandardVolumeFlow; - Units = Enum.GetValues(typeof(StandardVolumeFlowUnit)).Cast().Except(new StandardVolumeFlowUnit[]{ StandardVolumeFlowUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(StandardVolumeFlowUnit)).Cast().ToArray(); Zero = new StandardVolumeFlow(0, BaseUnit); Info = new QuantityInfo("StandardVolumeFlow", new UnitInfo[] @@ -72,7 +68,7 @@ static StandardVolumeFlow() new UnitInfo(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, "StandardCubicMetersPerSecond", BaseUnits.Undefined), new UnitInfo(StandardVolumeFlowUnit.StandardLiterPerMinute, "StandardLitersPerMinute", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.StandardVolumeFlow); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -86,9 +82,6 @@ static StandardVolumeFlow() /// If value is NaN or Infinity. public StandardVolumeFlow(double value, StandardVolumeFlowUnit unit) { - if (unit == StandardVolumeFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -132,24 +125,6 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) /// public static StandardVolumeFlowUnit BaseUnit { get; } - /// - /// Represents the largest possible value of StandardVolumeFlow - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static StandardVolumeFlow MaxValue { get; } - - /// - /// Represents the smallest possible value of StandardVolumeFlow - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static StandardVolumeFlow MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the StandardVolumeFlow quantity. /// @@ -169,6 +144,9 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -180,12 +158,6 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.StandardVolumeFlow; - /// /// The of this quantity. /// @@ -302,7 +274,7 @@ public static string GetAbbreviation(StandardVolumeFlowUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(StandardVolumeFlowUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -466,7 +438,7 @@ public static StandardVolumeFlow Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static StandardVolumeFlow Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -497,7 +469,7 @@ public static bool TryParse(string? str, out StandardVolumeFlow result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out StandardVolumeFlow result) { return QuantityParser.Default.TryParse( @@ -525,7 +497,7 @@ public static StandardVolumeFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -551,7 +523,7 @@ public static bool TryParseUnit(string str, out StandardVolumeFlowUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out StandardVolumeFlowUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -631,20 +603,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Stand return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(StandardVolumeFlow left, StandardVolumeFlow right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(StandardVolumeFlow left, StandardVolumeFlow right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -660,23 +618,6 @@ public int CompareTo(StandardVolumeFlow other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is StandardVolumeFlow objStandardVolumeFlow)) - return false; - - return Equals(objStandardVolumeFlow); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(StandardVolumeFlow other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another StandardVolumeFlow within the given absolute or relative tolerance. @@ -722,7 +663,7 @@ public bool Equals(StandardVolumeFlow other, double tolerance, ComparisonType co if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -748,10 +689,9 @@ public override int GetHashCode() public double As(StandardVolumeFlowUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -772,10 +712,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is StandardVolumeFlowUnit unitAsStandardVolumeFlowUnit)) + if (!(unit is StandardVolumeFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); - return As(unitAsStandardVolumeFlowUnit); + return (double)As(typedUnit); } /// @@ -864,10 +804,10 @@ private bool TryToUnit(StandardVolumeFlowUnit unit, out StandardVolumeFlow? conv /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is StandardVolumeFlowUnit unitAsStandardVolumeFlowUnit)) + 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(unitAsStandardVolumeFlowUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -911,63 +851,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1049,8 +955,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(StandardVolumeFlowUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return StandardVolumeFlow.QuantityType; else if (conversionType == typeof(QuantityInfo)) return StandardVolumeFlow.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index 4619946863..63807a9e1d 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics. /// [DataContract] - public readonly partial struct Temperature : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Temperature : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Temperature() { BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); BaseUnit = TemperatureUnit.Kelvin; - MaxValue = new Temperature(double.MaxValue, BaseUnit); - MinValue = new Temperature(double.MinValue, BaseUnit); - QuantityType = QuantityType.Temperature; - Units = Enum.GetValues(typeof(TemperatureUnit)).Cast().Except(new TemperatureUnit[]{ TemperatureUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TemperatureUnit)).Cast().ToArray(); Zero = new Temperature(0, BaseUnit); Info = new QuantityInfo("Temperature", new UnitInfo[] @@ -73,7 +69,7 @@ static Temperature() new UnitInfo(TemperatureUnit.MillidegreeCelsius, "MillidegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)), new UnitInfo(TemperatureUnit.SolarTemperature, "SolarTemperatures", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Temperature); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -87,9 +83,6 @@ static Temperature() /// If value is NaN or Infinity. public Temperature(double value, TemperatureUnit unit) { - if (unit == TemperatureUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -133,24 +126,6 @@ public Temperature(double value, UnitSystem unitSystem) /// public static TemperatureUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Temperature - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Temperature MaxValue { get; } - - /// - /// Represents the smallest possible value of Temperature - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Temperature MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Temperature quantity. /// @@ -170,6 +145,9 @@ public Temperature(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -181,12 +159,6 @@ public Temperature(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Temperature; - /// /// The of this quantity. /// @@ -311,7 +283,7 @@ public static string GetAbbreviation(TemperatureUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TemperatureUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -485,7 +457,7 @@ public static Temperature Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Temperature Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -516,7 +488,7 @@ public static bool TryParse(string? str, out Temperature result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Temperature result) { return QuantityParser.Default.TryParse( @@ -544,7 +516,7 @@ public static TemperatureUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -570,7 +542,7 @@ public static bool TryParseUnit(string str, out TemperatureUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -604,20 +576,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Temperature left, Temperature right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Temperature left, Temperature right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -633,23 +591,6 @@ public int CompareTo(Temperature other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Temperature objTemperature)) - return false; - - return Equals(objTemperature); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Temperature other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Temperature within the given absolute or relative tolerance. @@ -695,7 +636,7 @@ public bool Equals(Temperature other, double tolerance, ComparisonType compariso if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -721,10 +662,9 @@ public override int GetHashCode() public double As(TemperatureUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -745,10 +685,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TemperatureUnit unitAsTemperatureUnit)) + if (!(unit is TemperatureUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureUnit); + return (double)As(typedUnit); } /// @@ -839,10 +779,10 @@ private bool TryToUnit(TemperatureUnit unit, out Temperature? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureUnit unitAsTemperatureUnit)) + 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(unitAsTemperatureUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -886,63 +826,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1024,8 +930,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TemperatureUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Temperature.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Temperature.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index b966ee359d..ccdbef8d82 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time). /// [DataContract] - public readonly partial struct TemperatureChangeRate : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct TemperatureChangeRate : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static TemperatureChangeRate() { BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); BaseUnit = TemperatureChangeRateUnit.DegreeCelsiusPerSecond; - MaxValue = new TemperatureChangeRate(double.MaxValue, BaseUnit); - MinValue = new TemperatureChangeRate(double.MinValue, BaseUnit); - QuantityType = QuantityType.TemperatureChangeRate; - Units = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().Except(new TemperatureChangeRateUnit[]{ TemperatureChangeRateUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().ToArray(); Zero = new TemperatureChangeRate(0, BaseUnit); Info = new QuantityInfo("TemperatureChangeRate", new UnitInfo[] @@ -73,7 +69,7 @@ static TemperatureChangeRate() new UnitInfo(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, "MillidegreesCelsiusPerSecond", BaseUnits.Undefined), new UnitInfo(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "NanodegreesCelsiusPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.TemperatureChangeRate); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -87,9 +83,6 @@ static TemperatureChangeRate() /// If value is NaN or Infinity. public TemperatureChangeRate(double value, TemperatureChangeRateUnit unit) { - if (unit == TemperatureChangeRateUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -133,24 +126,6 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) /// public static TemperatureChangeRateUnit BaseUnit { get; } - /// - /// Represents the largest possible value of TemperatureChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TemperatureChangeRate MaxValue { get; } - - /// - /// Represents the smallest possible value of TemperatureChangeRate - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TemperatureChangeRate MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the TemperatureChangeRate quantity. /// @@ -170,6 +145,9 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -181,12 +159,6 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.TemperatureChangeRate; - /// /// The of this quantity. /// @@ -311,7 +283,7 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TemperatureChangeRateUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -485,7 +457,7 @@ public static TemperatureChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureChangeRate Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -516,7 +488,7 @@ public static bool TryParse(string? str, out TemperatureChangeRate result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out TemperatureChangeRate result) { return QuantityParser.Default.TryParse( @@ -544,7 +516,7 @@ public static TemperatureChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -570,7 +542,7 @@ public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureChangeRateUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -650,20 +622,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -679,23 +637,6 @@ public int CompareTo(TemperatureChangeRate other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is TemperatureChangeRate objTemperatureChangeRate)) - return false; - - return Equals(objTemperatureChangeRate); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(TemperatureChangeRate other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another TemperatureChangeRate within the given absolute or relative tolerance. @@ -741,7 +682,7 @@ public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -767,10 +708,9 @@ public override int GetHashCode() public double As(TemperatureChangeRateUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -791,10 +731,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TemperatureChangeRateUnit unitAsTemperatureChangeRateUnit)) + if (!(unit is TemperatureChangeRateUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureChangeRateUnit); + return (double)As(typedUnit); } /// @@ -885,10 +825,10 @@ private bool TryToUnit(TemperatureChangeRateUnit unit, out TemperatureChangeRate /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureChangeRateUnit unitAsTemperatureChangeRateUnit)) + 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(unitAsTemperatureChangeRateUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -932,63 +872,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1070,8 +976,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TemperatureChangeRateUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return TemperatureChangeRate.QuantityType; else if (conversionType == typeof(QuantityInfo)) return TemperatureChangeRate.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index 71e1401c59..c9d515069a 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Difference between two temperatures. The conversions are different than for Temperature. /// [DataContract] - public readonly partial struct TemperatureDelta : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct TemperatureDelta : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static TemperatureDelta() { BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); BaseUnit = TemperatureDeltaUnit.Kelvin; - MaxValue = new TemperatureDelta(double.MaxValue, BaseUnit); - MinValue = new TemperatureDelta(double.MinValue, BaseUnit); - QuantityType = QuantityType.TemperatureDelta; - Units = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().Except(new TemperatureDeltaUnit[]{ TemperatureDeltaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().ToArray(); Zero = new TemperatureDelta(0, BaseUnit); Info = new QuantityInfo("TemperatureDelta", new UnitInfo[] @@ -72,7 +68,7 @@ static TemperatureDelta() new UnitInfo(TemperatureDeltaUnit.Kelvin, "Kelvins", BaseUnits.Undefined), new UnitInfo(TemperatureDeltaUnit.MillidegreeCelsius, "MillidegreesCelsius", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.TemperatureDelta); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -86,9 +82,6 @@ static TemperatureDelta() /// If value is NaN or Infinity. public TemperatureDelta(double value, TemperatureDeltaUnit unit) { - if (unit == TemperatureDeltaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -132,24 +125,6 @@ public TemperatureDelta(double value, UnitSystem unitSystem) /// public static TemperatureDeltaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of TemperatureDelta - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TemperatureDelta MaxValue { get; } - - /// - /// Represents the smallest possible value of TemperatureDelta - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TemperatureDelta MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the TemperatureDelta quantity. /// @@ -169,6 +144,9 @@ public TemperatureDelta(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -180,12 +158,6 @@ public TemperatureDelta(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.TemperatureDelta; - /// /// The of this quantity. /// @@ -302,7 +274,7 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TemperatureDeltaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -466,7 +438,7 @@ public static TemperatureDelta Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureDelta Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -497,7 +469,7 @@ public static bool TryParse(string? str, out TemperatureDelta result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out TemperatureDelta result) { return QuantityParser.Default.TryParse( @@ -525,7 +497,7 @@ public static TemperatureDeltaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -551,7 +523,7 @@ public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureDeltaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -631,20 +603,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(TemperatureDelta left, TemperatureDelta right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(TemperatureDelta left, TemperatureDelta right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -660,23 +618,6 @@ public int CompareTo(TemperatureDelta other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is TemperatureDelta objTemperatureDelta)) - return false; - - return Equals(objTemperatureDelta); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(TemperatureDelta other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another TemperatureDelta within the given absolute or relative tolerance. @@ -722,7 +663,7 @@ public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -748,10 +689,9 @@ public override int GetHashCode() public double As(TemperatureDeltaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -772,10 +712,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TemperatureDeltaUnit unitAsTemperatureDeltaUnit)) + if (!(unit is TemperatureDeltaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureDeltaUnit); + return (double)As(typedUnit); } /// @@ -864,10 +804,10 @@ private bool TryToUnit(TemperatureDeltaUnit unit, out TemperatureDelta? converte /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureDeltaUnit unitAsTemperatureDeltaUnit)) + 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(unitAsTemperatureDeltaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -911,63 +851,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1049,8 +955,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TemperatureDeltaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return TemperatureDelta.QuantityType; else if (conversionType == typeof(QuantityInfo)) return TemperatureDelta.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs index 6a36994134..476aa2f8f5 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,10 +32,10 @@ namespace UnitsNet { /// /// - /// The rate of change of temperature with displacement in a given direction (as with increase of height) + /// /// [DataContract] - public readonly partial struct TemperatureGradient : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct TemperatureGradient : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static TemperatureGradient() { BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); BaseUnit = TemperatureGradientUnit.KelvinPerMeter; - MaxValue = new TemperatureGradient(double.MaxValue, BaseUnit); - MinValue = new TemperatureGradient(double.MinValue, BaseUnit); - QuantityType = QuantityType.TemperatureGradient; - Units = Enum.GetValues(typeof(TemperatureGradientUnit)).Cast().Except(new TemperatureGradientUnit[]{ TemperatureGradientUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TemperatureGradientUnit)).Cast().ToArray(); Zero = new TemperatureGradient(0, BaseUnit); Info = new QuantityInfo("TemperatureGradient", new UnitInfo[] @@ -67,7 +63,7 @@ static TemperatureGradient() new UnitInfo(TemperatureGradientUnit.DegreeFahrenheitPerFoot, "DegreesFahrenheitPerFoot", new BaseUnits(length: LengthUnit.Foot, temperature: TemperatureUnit.DegreeFahrenheit)), new UnitInfo(TemperatureGradientUnit.KelvinPerMeter, "KelvinsPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.Kelvin)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.TemperatureGradient); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static TemperatureGradient() /// If value is NaN or Infinity. public TemperatureGradient(double value, TemperatureGradientUnit unit) { - if (unit == TemperatureGradientUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public TemperatureGradient(double value, UnitSystem unitSystem) /// public static TemperatureGradientUnit BaseUnit { get; } - /// - /// Represents the largest possible value of TemperatureGradient - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TemperatureGradient MaxValue { get; } - - /// - /// Represents the smallest possible value of TemperatureGradient - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TemperatureGradient MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the TemperatureGradient quantity. /// @@ -164,6 +139,9 @@ public TemperatureGradient(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public TemperatureGradient(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.TemperatureGradient; - /// /// The of this quantity. /// @@ -257,7 +229,7 @@ public static string GetAbbreviation(TemperatureGradientUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TemperatureGradientUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -371,7 +343,7 @@ public static TemperatureGradient Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureGradient Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -402,7 +374,7 @@ public static bool TryParse(string? str, out TemperatureGradient result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out TemperatureGradient result) { return QuantityParser.Default.TryParse( @@ -430,7 +402,7 @@ public static TemperatureGradientUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -456,7 +428,7 @@ public static bool TryParseUnit(string str, out TemperatureGradientUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureGradientUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -536,20 +508,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Tempe return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(TemperatureGradient left, TemperatureGradient right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(TemperatureGradient left, TemperatureGradient right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -565,23 +523,6 @@ public int CompareTo(TemperatureGradient other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is TemperatureGradient objTemperatureGradient)) - return false; - - return Equals(objTemperatureGradient); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(TemperatureGradient other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another TemperatureGradient within the given absolute or relative tolerance. @@ -627,7 +568,7 @@ public bool Equals(TemperatureGradient other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -653,10 +594,9 @@ public override int GetHashCode() public double As(TemperatureGradientUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -677,10 +617,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TemperatureGradientUnit unitAsTemperatureGradientUnit)) + if (!(unit is TemperatureGradientUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); - return As(unitAsTemperatureGradientUnit); + return (double)As(typedUnit); } /// @@ -759,10 +699,10 @@ private bool TryToUnit(TemperatureGradientUnit unit, out TemperatureGradient? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TemperatureGradientUnit unitAsTemperatureGradientUnit)) + 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(unitAsTemperatureGradientUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -806,63 +746,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -944,8 +850,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TemperatureGradientUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return TemperatureGradient.QuantityType; else if (conversionType == typeof(QuantityInfo)) return TemperatureGradient.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index d7384e45ee..6c83353c45 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Thermal_Conductivity /// [DataContract] - public readonly partial struct ThermalConductivity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ThermalConductivity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static ThermalConductivity() { BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); BaseUnit = ThermalConductivityUnit.WattPerMeterKelvin; - MaxValue = new ThermalConductivity(double.MaxValue, BaseUnit); - MinValue = new ThermalConductivity(double.MinValue, BaseUnit); - QuantityType = QuantityType.ThermalConductivity; - Units = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().Except(new ThermalConductivityUnit[]{ ThermalConductivityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().ToArray(); Zero = new ThermalConductivity(0, BaseUnit); Info = new QuantityInfo("ThermalConductivity", new UnitInfo[] @@ -68,7 +64,7 @@ static ThermalConductivity() new UnitInfo(ThermalConductivityUnit.BtuPerHourFootFahrenheit, "BtusPerHourFootFahrenheit", BaseUnits.Undefined), new UnitInfo(ThermalConductivityUnit.WattPerMeterKelvin, "WattsPerMeterKelvin", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ThermalConductivity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -82,9 +78,6 @@ static ThermalConductivity() /// If value is NaN or Infinity. public ThermalConductivity(double value, ThermalConductivityUnit unit) { - if (unit == ThermalConductivityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -128,24 +121,6 @@ public ThermalConductivity(double value, UnitSystem unitSystem) /// public static ThermalConductivityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ThermalConductivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ThermalConductivity MaxValue { get; } - - /// - /// Represents the smallest possible value of ThermalConductivity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ThermalConductivity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ThermalConductivity quantity. /// @@ -165,6 +140,9 @@ public ThermalConductivity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -176,12 +154,6 @@ public ThermalConductivity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ThermalConductivity; - /// /// The of this quantity. /// @@ -242,7 +214,7 @@ public static string GetAbbreviation(ThermalConductivityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ThermalConductivityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -336,7 +308,7 @@ public static ThermalConductivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ThermalConductivity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -367,7 +339,7 @@ public static bool TryParse(string? str, out ThermalConductivity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ThermalConductivity result) { return QuantityParser.Default.TryParse( @@ -395,7 +367,7 @@ public static ThermalConductivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -421,7 +393,7 @@ public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ThermalConductivityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -501,20 +473,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Therm return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ThermalConductivity left, ThermalConductivity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ThermalConductivity left, ThermalConductivity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -530,23 +488,6 @@ public int CompareTo(ThermalConductivity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ThermalConductivity objThermalConductivity)) - return false; - - return Equals(objThermalConductivity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ThermalConductivity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ThermalConductivity within the given absolute or relative tolerance. @@ -592,7 +533,7 @@ public bool Equals(ThermalConductivity other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -618,10 +559,9 @@ public override int GetHashCode() public double As(ThermalConductivityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -642,10 +582,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ThermalConductivityUnit unitAsThermalConductivityUnit)) + if (!(unit is ThermalConductivityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); - return As(unitAsThermalConductivityUnit); + return (double)As(typedUnit); } /// @@ -720,10 +660,10 @@ private bool TryToUnit(ThermalConductivityUnit unit, out ThermalConductivity? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ThermalConductivityUnit unitAsThermalConductivityUnit)) + 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(unitAsThermalConductivityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -767,63 +707,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -905,8 +811,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ThermalConductivityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ThermalConductivity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ThermalConductivity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs index b16e6595a5..097a72be1e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. /// [DataContract] - public readonly partial struct ThermalResistance : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct ThermalResistance : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static ThermalResistance() { BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); BaseUnit = ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; - MaxValue = new ThermalResistance(double.MaxValue, BaseUnit); - MinValue = new ThermalResistance(double.MinValue, BaseUnit); - QuantityType = QuantityType.ThermalResistance; - Units = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().Except(new ThermalResistanceUnit[]{ ThermalResistanceUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().ToArray(); Zero = new ThermalResistance(0, BaseUnit); Info = new QuantityInfo("ThermalResistance", new UnitInfo[] @@ -69,7 +65,7 @@ static ThermalResistance() new UnitInfo(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, "SquareMeterKelvinsPerKilowatt", BaseUnits.Undefined), new UnitInfo(ThermalResistanceUnit.SquareMeterKelvinPerWatt, "SquareMeterKelvinsPerWatt", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.ThermalResistance); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static ThermalResistance() /// If value is NaN or Infinity. public ThermalResistance(double value, ThermalResistanceUnit unit) { - if (unit == ThermalResistanceUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public ThermalResistance(double value, UnitSystem unitSystem) /// public static ThermalResistanceUnit BaseUnit { get; } - /// - /// Represents the largest possible value of ThermalResistance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ThermalResistance MaxValue { get; } - - /// - /// Represents the smallest possible value of ThermalResistance - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static ThermalResistance MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the ThermalResistance quantity. /// @@ -166,6 +141,9 @@ public ThermalResistance(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public ThermalResistance(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.ThermalResistance; - /// /// The of this quantity. /// @@ -275,7 +247,7 @@ public static string GetAbbreviation(ThermalResistanceUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(ThermalResistanceUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -409,7 +381,7 @@ public static ThermalResistance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static ThermalResistance Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -440,7 +412,7 @@ public static bool TryParse(string? str, out ThermalResistance result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out ThermalResistance result) { return QuantityParser.Default.TryParse( @@ -468,7 +440,7 @@ public static ThermalResistanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -494,7 +466,7 @@ public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out ThermalResistanceUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -574,20 +546,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Therm return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(ThermalResistance left, ThermalResistance right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(ThermalResistance left, ThermalResistance right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -603,23 +561,6 @@ public int CompareTo(ThermalResistance other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is ThermalResistance objThermalResistance)) - return false; - - return Equals(objThermalResistance); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(ThermalResistance other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another ThermalResistance within the given absolute or relative tolerance. @@ -665,7 +606,7 @@ public bool Equals(ThermalResistance other, double tolerance, ComparisonType com if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -691,10 +632,9 @@ public override int GetHashCode() public double As(ThermalResistanceUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -715,10 +655,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is ThermalResistanceUnit unitAsThermalResistanceUnit)) + if (!(unit is ThermalResistanceUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); - return As(unitAsThermalResistanceUnit); + return (double)As(typedUnit); } /// @@ -801,10 +741,10 @@ private bool TryToUnit(ThermalResistanceUnit unit, out ThermalResistance? conver /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is ThermalResistanceUnit unitAsThermalResistanceUnit)) + 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(unitAsThermalResistanceUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -848,63 +788,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -986,8 +892,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(ThermalResistanceUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return ThermalResistance.QuantityType; else if (conversionType == typeof(QuantityInfo)) return ThermalResistance.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index fd38232f77..6caeee53be 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt. /// [DataContract] - public readonly partial struct Torque : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Torque : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Torque() { BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); BaseUnit = TorqueUnit.NewtonMeter; - MaxValue = new Torque(double.MaxValue, BaseUnit); - MinValue = new Torque(double.MinValue, BaseUnit); - QuantityType = QuantityType.Torque; - Units = Enum.GetValues(typeof(TorqueUnit)).Cast().Except(new TorqueUnit[]{ TorqueUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TorqueUnit)).Cast().ToArray(); Zero = new Torque(0, BaseUnit); Info = new QuantityInfo("Torque", new UnitInfo[] @@ -88,7 +84,7 @@ static Torque() new UnitInfo(TorqueUnit.TonneForceMeter, "TonneForceMeters", BaseUnits.Undefined), new UnitInfo(TorqueUnit.TonneForceMillimeter, "TonneForceMillimeters", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Torque); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -102,9 +98,6 @@ static Torque() /// If value is NaN or Infinity. public Torque(double value, TorqueUnit unit) { - if (unit == TorqueUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -148,24 +141,6 @@ public Torque(double value, UnitSystem unitSystem) /// public static TorqueUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Torque - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Torque MaxValue { get; } - - /// - /// Represents the smallest possible value of Torque - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Torque MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Torque quantity. /// @@ -185,6 +160,9 @@ public Torque(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -196,12 +174,6 @@ public Torque(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Torque; - /// /// The of this quantity. /// @@ -449,7 +421,7 @@ public static string GetAbbreviation(TorqueUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TorqueUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -773,7 +745,7 @@ public static Torque Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Torque Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -804,7 +776,7 @@ public static bool TryParse(string? str, out Torque result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Torque result) { return QuantityParser.Default.TryParse( @@ -832,7 +804,7 @@ public static TorqueUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -858,7 +830,7 @@ public static bool TryParseUnit(string str, out TorqueUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TorqueUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -938,20 +910,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Torqu return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Torque left, Torque right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Torque left, Torque right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -967,23 +925,6 @@ public int CompareTo(Torque other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Torque objTorque)) - return false; - - return Equals(objTorque); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Torque other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Torque within the given absolute or relative tolerance. @@ -1029,7 +970,7 @@ public bool Equals(Torque other, double tolerance, ComparisonType comparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1055,10 +996,9 @@ public override int GetHashCode() public double As(TorqueUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1079,10 +1019,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TorqueUnit unitAsTorqueUnit)) + if (!(unit is TorqueUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); - return As(unitAsTorqueUnit); + return (double)As(typedUnit); } /// @@ -1203,10 +1143,10 @@ private bool TryToUnit(TorqueUnit unit, out Torque? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TorqueUnit unitAsTorqueUnit)) + 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(unitAsTorqueUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1250,63 +1190,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1388,8 +1294,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TorqueUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Torque.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Torque.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs index e8f59c7066..d70cf4f425 100644 --- a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// The magnitude of torque per unit length. /// [DataContract] - public readonly partial struct TorquePerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct TorquePerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static TorquePerLength() { BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); BaseUnit = TorquePerLengthUnit.NewtonMeterPerMeter; - MaxValue = new TorquePerLength(double.MaxValue, BaseUnit); - MinValue = new TorquePerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.TorquePerLength; - Units = Enum.GetValues(typeof(TorquePerLengthUnit)).Cast().Except(new TorquePerLengthUnit[]{ TorquePerLengthUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TorquePerLengthUnit)).Cast().ToArray(); Zero = new TorquePerLength(0, BaseUnit); Info = new QuantityInfo("TorquePerLength", new UnitInfo[] @@ -84,7 +80,7 @@ static TorquePerLength() new UnitInfo(TorquePerLengthUnit.TonneForceMeterPerMeter, "TonneForceMetersPerMeter", BaseUnits.Undefined), new UnitInfo(TorquePerLengthUnit.TonneForceMillimeterPerMeter, "TonneForceMillimetersPerMeter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.TorquePerLength); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -98,9 +94,6 @@ static TorquePerLength() /// If value is NaN or Infinity. public TorquePerLength(double value, TorquePerLengthUnit unit) { - if (unit == TorquePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -144,24 +137,6 @@ public TorquePerLength(double value, UnitSystem unitSystem) /// public static TorquePerLengthUnit BaseUnit { get; } - /// - /// Represents the largest possible value of TorquePerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TorquePerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of TorquePerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static TorquePerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the TorquePerLength quantity. /// @@ -181,6 +156,9 @@ public TorquePerLength(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -192,12 +170,6 @@ public TorquePerLength(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.TorquePerLength; - /// /// The of this quantity. /// @@ -413,7 +385,7 @@ public static string GetAbbreviation(TorquePerLengthUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TorquePerLengthUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -697,7 +669,7 @@ public static TorquePerLength Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static TorquePerLength Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -728,7 +700,7 @@ public static bool TryParse(string? str, out TorquePerLength result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out TorquePerLength result) { return QuantityParser.Default.TryParse( @@ -756,7 +728,7 @@ public static TorquePerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -782,7 +754,7 @@ public static bool TryParseUnit(string str, out TorquePerLengthUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TorquePerLengthUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -862,20 +834,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Torqu return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(TorquePerLength left, TorquePerLength right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(TorquePerLength left, TorquePerLength right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -891,23 +849,6 @@ public int CompareTo(TorquePerLength other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is TorquePerLength objTorquePerLength)) - return false; - - return Equals(objTorquePerLength); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(TorquePerLength other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another TorquePerLength within the given absolute or relative tolerance. @@ -953,7 +894,7 @@ public bool Equals(TorquePerLength other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -979,10 +920,9 @@ public override int GetHashCode() public double As(TorquePerLengthUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1003,10 +943,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TorquePerLengthUnit unitAsTorquePerLengthUnit)) + if (!(unit is TorquePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsTorquePerLengthUnit); + return (double)As(typedUnit); } /// @@ -1119,10 +1059,10 @@ private bool TryToUnit(TorquePerLengthUnit unit, out TorquePerLength? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TorquePerLengthUnit unitAsTorquePerLengthUnit)) + 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(unitAsTorquePerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1166,63 +1106,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1304,8 +1210,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TorquePerLengthUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return TorquePerLength.QuantityType; else if (conversionType == typeof(QuantityInfo)) return TorquePerLength.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs index fc6b7fb8e4..fe876e38dc 100644 --- a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Turbidity /// [DataContract] - public readonly partial struct Turbidity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Turbidity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,17 +56,14 @@ static Turbidity() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = TurbidityUnit.NTU; - MaxValue = new Turbidity(double.MaxValue, BaseUnit); - MinValue = new Turbidity(double.MinValue, BaseUnit); - QuantityType = QuantityType.Turbidity; - Units = Enum.GetValues(typeof(TurbidityUnit)).Cast().Except(new TurbidityUnit[]{ TurbidityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(TurbidityUnit)).Cast().ToArray(); Zero = new Turbidity(0, BaseUnit); Info = new QuantityInfo("Turbidity", new UnitInfo[] { new UnitInfo(TurbidityUnit.NTU, "NTU", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Turbidity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -81,9 +77,6 @@ static Turbidity() /// If value is NaN or Infinity. public Turbidity(double value, TurbidityUnit unit) { - if (unit == TurbidityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -127,24 +120,6 @@ public Turbidity(double value, UnitSystem unitSystem) /// public static TurbidityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Turbidity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Turbidity MaxValue { get; } - - /// - /// Represents the smallest possible value of Turbidity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Turbidity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Turbidity quantity. /// @@ -164,6 +139,9 @@ public Turbidity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -175,12 +153,6 @@ public Turbidity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Turbidity; - /// /// The of this quantity. /// @@ -233,7 +205,7 @@ public static string GetAbbreviation(TurbidityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(TurbidityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -317,7 +289,7 @@ public static Turbidity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Turbidity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -348,7 +320,7 @@ public static bool TryParse(string? str, out Turbidity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Turbidity result) { return QuantityParser.Default.TryParse( @@ -376,7 +348,7 @@ public static TurbidityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -402,7 +374,7 @@ public static bool TryParseUnit(string str, out TurbidityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out TurbidityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -482,20 +454,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Turbi return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Turbidity left, Turbidity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Turbidity left, Turbidity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -511,23 +469,6 @@ public int CompareTo(Turbidity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Turbidity objTurbidity)) - return false; - - return Equals(objTurbidity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Turbidity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Turbidity within the given absolute or relative tolerance. @@ -573,7 +514,7 @@ public bool Equals(Turbidity other, double tolerance, ComparisonType comparisonT if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -599,10 +540,9 @@ public override int GetHashCode() public double As(TurbidityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -623,10 +563,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is TurbidityUnit unitAsTurbidityUnit)) + if (!(unit is TurbidityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); - return As(unitAsTurbidityUnit); + return (double)As(typedUnit); } /// @@ -699,10 +639,10 @@ private bool TryToUnit(TurbidityUnit unit, out Turbidity? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is TurbidityUnit unitAsTurbidityUnit)) + 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(unitAsTurbidityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -746,63 +686,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -884,8 +790,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(TurbidityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Turbidity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Turbidity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index 5fac2a188b..9dd24f9ba5 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. /// [DataContract] - public readonly partial struct VitaminA : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct VitaminA : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,17 +53,14 @@ static VitaminA() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = VitaminAUnit.InternationalUnit; - MaxValue = new VitaminA(double.MaxValue, BaseUnit); - MinValue = new VitaminA(double.MinValue, BaseUnit); - QuantityType = QuantityType.VitaminA; - Units = Enum.GetValues(typeof(VitaminAUnit)).Cast().Except(new VitaminAUnit[]{ VitaminAUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VitaminAUnit)).Cast().ToArray(); Zero = new VitaminA(0, BaseUnit); Info = new QuantityInfo("VitaminA", new UnitInfo[] { new UnitInfo(VitaminAUnit.InternationalUnit, "InternationalUnits", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.VitaminA); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -78,9 +74,6 @@ static VitaminA() /// If value is NaN or Infinity. public VitaminA(double value, VitaminAUnit unit) { - if (unit == VitaminAUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -124,24 +117,6 @@ public VitaminA(double value, UnitSystem unitSystem) /// public static VitaminAUnit BaseUnit { get; } - /// - /// Represents the largest possible value of VitaminA - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VitaminA MaxValue { get; } - - /// - /// Represents the smallest possible value of VitaminA - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VitaminA MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the VitaminA quantity. /// @@ -161,6 +136,9 @@ public VitaminA(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -172,12 +150,6 @@ public VitaminA(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.VitaminA; - /// /// The of this quantity. /// @@ -230,7 +202,7 @@ public static string GetAbbreviation(VitaminAUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VitaminAUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -314,7 +286,7 @@ public static VitaminA Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static VitaminA Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -345,7 +317,7 @@ public static bool TryParse(string? str, out VitaminA result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out VitaminA result) { return QuantityParser.Default.TryParse( @@ -373,7 +345,7 @@ public static VitaminAUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -399,7 +371,7 @@ public static bool TryParseUnit(string str, out VitaminAUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VitaminAUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -479,20 +451,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Vitam return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(VitaminA left, VitaminA right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(VitaminA left, VitaminA right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -508,23 +466,6 @@ public int CompareTo(VitaminA other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is VitaminA objVitaminA)) - return false; - - return Equals(objVitaminA); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(VitaminA other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another VitaminA within the given absolute or relative tolerance. @@ -570,7 +511,7 @@ public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonTy if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -596,10 +537,9 @@ public override int GetHashCode() public double As(VitaminAUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -620,10 +560,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VitaminAUnit unitAsVitaminAUnit)) + if (!(unit is VitaminAUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); - return As(unitAsVitaminAUnit); + return (double)As(typedUnit); } /// @@ -696,10 +636,10 @@ private bool TryToUnit(VitaminAUnit unit, out VitaminA? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VitaminAUnit unitAsVitaminAUnit)) + 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(unitAsVitaminAUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -743,63 +683,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -881,8 +787,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VitaminAUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return VitaminA.QuantityType; else if (conversionType == typeof(QuantityInfo)) return VitaminA.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index 5a208965a3..63f7be1c53 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces. /// [DataContract] - public readonly partial struct Volume : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct Volume : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static Volume() { BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); BaseUnit = VolumeUnit.CubicMeter; - MaxValue = new Volume(double.MaxValue, BaseUnit); - MinValue = new Volume(double.MinValue, BaseUnit); - QuantityType = QuantityType.Volume; - Units = Enum.GetValues(typeof(VolumeUnit)).Cast().Except(new VolumeUnit[]{ VolumeUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VolumeUnit)).Cast().ToArray(); Zero = new Volume(0, BaseUnit); Info = new QuantityInfo("Volume", new UnitInfo[] @@ -115,7 +111,7 @@ static Volume() new UnitInfo(VolumeUnit.UsTablespoon, "UsTablespoons", BaseUnits.Undefined), new UnitInfo(VolumeUnit.UsTeaspoon, "UsTeaspoons", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.Volume); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -129,9 +125,6 @@ static Volume() /// If value is NaN or Infinity. public Volume(double value, VolumeUnit unit) { - if (unit == VolumeUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -175,24 +168,6 @@ public Volume(double value, UnitSystem unitSystem) /// public static VolumeUnit BaseUnit { get; } - /// - /// Represents the largest possible value of Volume - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Volume MaxValue { get; } - - /// - /// Represents the smallest possible value of Volume - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static Volume MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the Volume quantity. /// @@ -212,6 +187,9 @@ public Volume(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -223,12 +201,6 @@ public Volume(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.Volume; - /// /// The of this quantity. /// @@ -736,7 +708,7 @@ public static string GetAbbreviation(VolumeUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VolumeUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1330,7 +1302,7 @@ public static Volume Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static Volume Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1361,7 +1333,7 @@ public static bool TryParse(string? str, out Volume result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out Volume result) { return QuantityParser.Default.TryParse( @@ -1389,7 +1361,7 @@ public static VolumeUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1415,7 +1387,7 @@ public static bool TryParseUnit(string str, out VolumeUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1495,20 +1467,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(Volume left, Volume right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(Volume left, Volume right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1524,23 +1482,6 @@ public int CompareTo(Volume other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is Volume objVolume)) - return false; - - return Equals(objVolume); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(Volume other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another Volume within the given absolute or relative tolerance. @@ -1586,7 +1527,7 @@ public bool Equals(Volume other, double tolerance, ComparisonType comparisonType if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1612,10 +1553,9 @@ public override int GetHashCode() public double As(VolumeUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1636,10 +1576,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VolumeUnit unitAsVolumeUnit)) + if (!(unit is VolumeUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeUnit); + return (double)As(typedUnit); } /// @@ -1814,10 +1754,10 @@ private bool TryToUnit(VolumeUnit unit, out Volume? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeUnit unitAsVolumeUnit)) + 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(unitAsVolumeUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1861,63 +1801,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1999,8 +1905,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VolumeUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return Volume.QuantityType; else if (conversionType == typeof(QuantityInfo)) return Volume.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs index 3e2901a70f..089da3c52e 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Concentration#Volume_concentration /// [DataContract] - public readonly partial struct VolumeConcentration : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct VolumeConcentration : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static VolumeConcentration() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = VolumeConcentrationUnit.DecimalFraction; - MaxValue = new VolumeConcentration(double.MaxValue, BaseUnit); - MinValue = new VolumeConcentration(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumeConcentration; - Units = Enum.GetValues(typeof(VolumeConcentrationUnit)).Cast().Except(new VolumeConcentrationUnit[]{ VolumeConcentrationUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VolumeConcentrationUnit)).Cast().ToArray(); Zero = new VolumeConcentration(0, BaseUnit); Info = new QuantityInfo("VolumeConcentration", new UnitInfo[] @@ -86,7 +82,7 @@ static VolumeConcentration() new UnitInfo(VolumeConcentrationUnit.PicolitersPerLiter, "PicolitersPerLiter", BaseUnits.Undefined), new UnitInfo(VolumeConcentrationUnit.PicolitersPerMililiter, "PicolitersPerMililiter", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.VolumeConcentration); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -100,9 +96,6 @@ static VolumeConcentration() /// If value is NaN or Infinity. public VolumeConcentration(double value, VolumeConcentrationUnit unit) { - if (unit == VolumeConcentrationUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -146,24 +139,6 @@ public VolumeConcentration(double value, UnitSystem unitSystem) /// public static VolumeConcentrationUnit BaseUnit { get; } - /// - /// Represents the largest possible value of VolumeConcentration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumeConcentration MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumeConcentration - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumeConcentration MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the VolumeConcentration quantity. /// @@ -183,6 +158,9 @@ public VolumeConcentration(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -194,12 +172,6 @@ public VolumeConcentration(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.VolumeConcentration; - /// /// The of this quantity. /// @@ -404,7 +376,7 @@ public static string GetAbbreviation(VolumeConcentrationUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VolumeConcentrationUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -678,7 +650,7 @@ public static VolumeConcentration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static VolumeConcentration Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -709,7 +681,7 @@ public static bool TryParse(string? str, out VolumeConcentration result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out VolumeConcentration result) { return QuantityParser.Default.TryParse( @@ -737,7 +709,7 @@ public static VolumeConcentrationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -763,7 +735,7 @@ public static bool TryParseUnit(string str, out VolumeConcentrationUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeConcentrationUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -843,20 +815,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(VolumeConcentration left, VolumeConcentration right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(VolumeConcentration left, VolumeConcentration right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -872,23 +830,6 @@ public int CompareTo(VolumeConcentration other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumeConcentration objVolumeConcentration)) - return false; - - return Equals(objVolumeConcentration); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(VolumeConcentration other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another VolumeConcentration within the given absolute or relative tolerance. @@ -934,7 +875,7 @@ public bool Equals(VolumeConcentration other, double tolerance, ComparisonType c if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -960,10 +901,9 @@ public override int GetHashCode() public double As(VolumeConcentrationUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -984,10 +924,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VolumeConcentrationUnit unitAsVolumeConcentrationUnit)) + if (!(unit is VolumeConcentrationUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeConcentrationUnit); + return (double)As(typedUnit); } /// @@ -1098,10 +1038,10 @@ private bool TryToUnit(VolumeConcentrationUnit unit, out VolumeConcentration? co /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeConcentrationUnit unitAsVolumeConcentrationUnit)) + 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(unitAsVolumeConcentrationUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -1145,63 +1085,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1283,8 +1189,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VolumeConcentrationUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return VolumeConcentration.QuantityType; else if (conversionType == typeof(QuantityInfo)) return VolumeConcentration.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index a71003523f..7c908f8629 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q. /// [DataContract] - public readonly partial struct VolumeFlow : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct VolumeFlow : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static VolumeFlow() { BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); BaseUnit = VolumeFlowUnit.CubicMeterPerSecond; - MaxValue = new VolumeFlow(double.MaxValue, BaseUnit); - MinValue = new VolumeFlow(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumeFlow; - Units = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().Except(new VolumeFlowUnit[]{ VolumeFlowUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().ToArray(); Zero = new VolumeFlow(0, BaseUnit); Info = new QuantityInfo("VolumeFlow", new UnitInfo[] @@ -107,7 +103,7 @@ static VolumeFlow() new UnitInfo(VolumeFlowUnit.MilliliterPerHour, "MillilitersPerHour", BaseUnits.Undefined), new UnitInfo(VolumeFlowUnit.MilliliterPerMinute, "MillilitersPerMinute", BaseUnits.Undefined), new UnitInfo(VolumeFlowUnit.MilliliterPerSecond, "MillilitersPerSecond", BaseUnits.Undefined), - new UnitInfo(VolumeFlowUnit.MillionUsGallonsPerDay, "MillionUsGallonsPerDay", BaseUnits.Undefined), + new UnitInfo(VolumeFlowUnit.MillionUsGallonPerDay, "MillionUsGallonsPerDay", BaseUnits.Undefined), new UnitInfo(VolumeFlowUnit.NanoliterPerDay, "NanolitersPerDay", BaseUnits.Undefined), new UnitInfo(VolumeFlowUnit.NanoliterPerHour, "NanolitersPerHour", BaseUnits.Undefined), new UnitInfo(VolumeFlowUnit.NanoliterPerMinute, "NanolitersPerMinute", BaseUnits.Undefined), @@ -125,7 +121,7 @@ static VolumeFlow() new UnitInfo(VolumeFlowUnit.UsGallonPerMinute, "UsGallonsPerMinute", BaseUnits.Undefined), new UnitInfo(VolumeFlowUnit.UsGallonPerSecond, "UsGallonsPerSecond", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.VolumeFlow); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -139,9 +135,6 @@ static VolumeFlow() /// If value is NaN or Infinity. public VolumeFlow(double value, VolumeFlowUnit unit) { - if (unit == VolumeFlowUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -185,24 +178,6 @@ public VolumeFlow(double value, UnitSystem unitSystem) /// public static VolumeFlowUnit BaseUnit { get; } - /// - /// Represents the largest possible value of VolumeFlow - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumeFlow MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumeFlow - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumeFlow MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the VolumeFlow quantity. /// @@ -222,6 +197,9 @@ public VolumeFlow(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -233,12 +211,6 @@ public VolumeFlow(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.VolumeFlow; - /// /// The of this quantity. /// @@ -474,9 +446,9 @@ public VolumeFlow(double value, UnitSystem unitSystem) public double MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); + public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonPerDay); /// /// Gets a value of this quantity converted into @@ -613,7 +585,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MillionUsGallonsPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction(VolumeFlowUnit.MillionUsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); @@ -679,7 +651,7 @@ internal static void RegisterDefaultConversions(UnitConverter unitConverter) unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerHour)); unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerMinute)); unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonsPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MillionUsGallonsPerDay)); + unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MillionUsGallonPerDay)); unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerDay)); unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerHour)); unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerMinute)); @@ -769,7 +741,7 @@ internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbrev 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.MillionUsGallonsPerDay, new CultureInfo("en-US"), false, true, new string[]{"MGD"}); + 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[]{"нл/ч"}); @@ -806,7 +778,7 @@ public static string GetAbbreviation(VolumeFlowUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VolumeFlowUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -1267,13 +1239,13 @@ public static VolumeFlow FromMillilitersPerSecond(QuantityValue millilitersperse } /// - /// Creates a from . + /// Creates a from . /// /// If value is NaN or Infinity. public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) { double value = (double) millionusgallonsperday; - return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonPerDay); } /// @@ -1500,7 +1472,7 @@ public static VolumeFlow Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static VolumeFlow Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -1531,7 +1503,7 @@ public static bool TryParse(string? str, out VolumeFlow result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out VolumeFlow result) { return QuantityParser.Default.TryParse( @@ -1559,7 +1531,7 @@ public static VolumeFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1585,7 +1557,7 @@ public static bool TryParseUnit(string str, out VolumeFlowUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeFlowUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -1665,20 +1637,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(VolumeFlow left, VolumeFlow right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(VolumeFlow left, VolumeFlow right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -1694,23 +1652,6 @@ public int CompareTo(VolumeFlow other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumeFlow objVolumeFlow)) - return false; - - return Equals(objVolumeFlow); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(VolumeFlow other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another VolumeFlow within the given absolute or relative tolerance. @@ -1756,7 +1697,7 @@ public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparison if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -1782,10 +1723,9 @@ public override int GetHashCode() public double As(VolumeFlowUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -1806,10 +1746,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VolumeFlowUnit unitAsVolumeFlowUnit)) + if (!(unit is VolumeFlowUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeFlowUnit); + return (double)As(typedUnit); } /// @@ -1914,7 +1854,7 @@ private bool TryToUnit(VolumeFlowUnit unit, out VolumeFlow? converted) (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.MillionUsGallonsPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 22.824465227, 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), @@ -1977,7 +1917,7 @@ private bool TryToUnit(VolumeFlowUnit unit, out VolumeFlow? converted) (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.MillionUsGallonsPerDay) => new VolumeFlow(_value * 22.824465227, VolumeFlowUnit.MillionUsGallonsPerDay), + (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), @@ -2004,10 +1944,10 @@ private bool TryToUnit(VolumeFlowUnit unit, out VolumeFlow? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeFlowUnit unitAsVolumeFlowUnit)) + 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(unitAsVolumeFlowUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -2051,63 +1991,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -2189,8 +2095,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VolumeFlowUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return VolumeFlow.QuantityType; else if (conversionType == typeof(QuantityInfo)) return VolumeFlow.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index 0f365e62e8..765b992554 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,10 +32,10 @@ namespace UnitsNet { /// /// - /// The volumetric flow rate per area is the volume of fluid which passes through a given unit surface area per unit time. + /// /// [DataContract] - public readonly partial struct VolumeFlowPerArea : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct VolumeFlowPerArea : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static VolumeFlowPerArea() { BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); BaseUnit = VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter; - MaxValue = new VolumeFlowPerArea(double.MaxValue, BaseUnit); - MinValue = new VolumeFlowPerArea(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumeFlowPerArea; - Units = Enum.GetValues(typeof(VolumeFlowPerAreaUnit)).Cast().Except(new VolumeFlowPerAreaUnit[]{ VolumeFlowPerAreaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VolumeFlowPerAreaUnit)).Cast().ToArray(); Zero = new VolumeFlowPerArea(0, BaseUnit); Info = new QuantityInfo("VolumeFlowPerArea", new UnitInfo[] @@ -65,7 +61,7 @@ static VolumeFlowPerArea() new UnitInfo(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, "CubicFeetPerMinutePerSquareFoot", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)), new UnitInfo(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "CubicMetersPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.VolumeFlowPerArea); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -79,9 +75,6 @@ static VolumeFlowPerArea() /// If value is NaN or Infinity. public VolumeFlowPerArea(double value, VolumeFlowPerAreaUnit unit) { - if (unit == VolumeFlowPerAreaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -125,24 +118,6 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) /// public static VolumeFlowPerAreaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of VolumeFlowPerArea - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumeFlowPerArea MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumeFlowPerArea - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumeFlowPerArea MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the VolumeFlowPerArea quantity. /// @@ -162,6 +137,9 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -173,12 +151,6 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.VolumeFlowPerArea; - /// /// The of this quantity. /// @@ -239,7 +211,7 @@ public static string GetAbbreviation(VolumeFlowPerAreaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VolumeFlowPerAreaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -333,7 +305,7 @@ public static VolumeFlowPerArea Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static VolumeFlowPerArea Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -364,7 +336,7 @@ public static bool TryParse(string? str, out VolumeFlowPerArea result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out VolumeFlowPerArea result) { return QuantityParser.Default.TryParse( @@ -392,7 +364,7 @@ public static VolumeFlowPerAreaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -418,7 +390,7 @@ public static bool TryParseUnit(string str, out VolumeFlowPerAreaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeFlowPerAreaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -498,20 +470,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(VolumeFlowPerArea left, VolumeFlowPerArea right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(VolumeFlowPerArea left, VolumeFlowPerArea right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -527,23 +485,6 @@ public int CompareTo(VolumeFlowPerArea other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumeFlowPerArea objVolumeFlowPerArea)) - return false; - - return Equals(objVolumeFlowPerArea); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(VolumeFlowPerArea other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another VolumeFlowPerArea within the given absolute or relative tolerance. @@ -589,7 +530,7 @@ public bool Equals(VolumeFlowPerArea other, double tolerance, ComparisonType com if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -615,10 +556,9 @@ public override int GetHashCode() public double As(VolumeFlowPerAreaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -639,10 +579,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VolumeFlowPerAreaUnit unitAsVolumeFlowPerAreaUnit)) + if (!(unit is VolumeFlowPerAreaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); - return As(unitAsVolumeFlowPerAreaUnit); + return (double)As(typedUnit); } /// @@ -717,10 +657,10 @@ private bool TryToUnit(VolumeFlowPerAreaUnit unit, out VolumeFlowPerArea? conver /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumeFlowPerAreaUnit unitAsVolumeFlowPerAreaUnit)) + 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(unitAsVolumeFlowPerAreaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -764,63 +704,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -902,8 +808,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VolumeFlowPerAreaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return VolumeFlowPerArea.QuantityType; else if (conversionType == typeof(QuantityInfo)) return VolumeFlowPerArea.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs index 89f78b1d72..3feec62585 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// Volume, typically of fluid, that a container can hold within a unit of length. /// [DataContract] - public readonly partial struct VolumePerLength : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct VolumePerLength : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static VolumePerLength() { BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); BaseUnit = VolumePerLengthUnit.CubicMeterPerMeter; - MaxValue = new VolumePerLength(double.MaxValue, BaseUnit); - MinValue = new VolumePerLength(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumePerLength; - Units = Enum.GetValues(typeof(VolumePerLengthUnit)).Cast().Except(new VolumePerLengthUnit[]{ VolumePerLengthUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VolumePerLengthUnit)).Cast().ToArray(); Zero = new VolumePerLength(0, BaseUnit); Info = new QuantityInfo("VolumePerLength", new UnitInfo[] @@ -70,7 +66,7 @@ static VolumePerLength() new UnitInfo(VolumePerLengthUnit.LiterPerMillimeter, "LitersPerMillimeter", BaseUnits.Undefined), new UnitInfo(VolumePerLengthUnit.OilBarrelPerFoot, "OilBarrelsPerFoot", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.VolumePerLength); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -84,9 +80,6 @@ static VolumePerLength() /// If value is NaN or Infinity. public VolumePerLength(double value, VolumePerLengthUnit unit) { - if (unit == VolumePerLengthUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -130,24 +123,6 @@ public VolumePerLength(double value, UnitSystem unitSystem) /// public static VolumePerLengthUnit BaseUnit { get; } - /// - /// Represents the largest possible value of VolumePerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumePerLength MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumePerLength - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumePerLength MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the VolumePerLength quantity. /// @@ -167,6 +142,9 @@ public VolumePerLength(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -178,12 +156,6 @@ public VolumePerLength(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.VolumePerLength; - /// /// The of this quantity. /// @@ -284,7 +256,7 @@ public static string GetAbbreviation(VolumePerLengthUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VolumePerLengthUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -428,7 +400,7 @@ public static VolumePerLength Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static VolumePerLength Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -459,7 +431,7 @@ public static bool TryParse(string? str, out VolumePerLength result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out VolumePerLength result) { return QuantityParser.Default.TryParse( @@ -487,7 +459,7 @@ public static VolumePerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -513,7 +485,7 @@ public static bool TryParseUnit(string str, out VolumePerLengthUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumePerLengthUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -593,20 +565,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(VolumePerLength left, VolumePerLength right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(VolumePerLength left, VolumePerLength right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -622,23 +580,6 @@ public int CompareTo(VolumePerLength other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumePerLength objVolumePerLength)) - return false; - - return Equals(objVolumePerLength); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(VolumePerLength other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another VolumePerLength within the given absolute or relative tolerance. @@ -684,7 +625,7 @@ public bool Equals(VolumePerLength other, double tolerance, ComparisonType compa if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -710,10 +651,9 @@ public override int GetHashCode() public double As(VolumePerLengthUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -734,10 +674,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VolumePerLengthUnit unitAsVolumePerLengthUnit)) + if (!(unit is VolumePerLengthUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); - return As(unitAsVolumePerLengthUnit); + return (double)As(typedUnit); } /// @@ -822,10 +762,10 @@ private bool TryToUnit(VolumePerLengthUnit unit, out VolumePerLength? converted) /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumePerLengthUnit unitAsVolumePerLengthUnit)) + 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(unitAsVolumePerLengthUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -869,63 +809,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1007,8 +913,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VolumePerLengthUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return VolumePerLength.QuantityType; else if (conversionType == typeof(QuantityInfo)) return VolumePerLength.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index 3a5aa6c952..1eb4353947 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -39,7 +38,7 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Volumetric_heat_capacity /// [DataContract] - public readonly partial struct VolumetricHeatCapacity : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct VolumetricHeatCapacity : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -57,10 +56,7 @@ static VolumetricHeatCapacity() { BaseDimensions = new BaseDimensions(-1, 1, -2, 0, -1, 0, 0); BaseUnit = VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin; - MaxValue = new VolumetricHeatCapacity(double.MaxValue, BaseUnit); - MinValue = new VolumetricHeatCapacity(double.MinValue, BaseUnit); - QuantityType = QuantityType.VolumetricHeatCapacity; - Units = Enum.GetValues(typeof(VolumetricHeatCapacityUnit)).Cast().Except(new VolumetricHeatCapacityUnit[]{ VolumetricHeatCapacityUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(VolumetricHeatCapacityUnit)).Cast().ToArray(); Zero = new VolumetricHeatCapacity(0, BaseUnit); Info = new QuantityInfo("VolumetricHeatCapacity", new UnitInfo[] @@ -75,7 +71,7 @@ static VolumetricHeatCapacity() new UnitInfo(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, "MegajoulesPerCubicMeterDegreeCelsius", BaseUnits.Undefined), new UnitInfo(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MegajoulesPerCubicMeterKelvin", BaseUnits.Undefined), }, - BaseUnit, Zero, BaseDimensions, QuantityType.VolumetricHeatCapacity); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -89,9 +85,6 @@ static VolumetricHeatCapacity() /// If value is NaN or Infinity. public VolumetricHeatCapacity(double value, VolumetricHeatCapacityUnit unit) { - if (unit == VolumetricHeatCapacityUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -135,24 +128,6 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) /// public static VolumetricHeatCapacityUnit BaseUnit { get; } - /// - /// Represents the largest possible value of VolumetricHeatCapacity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumetricHeatCapacity MaxValue { get; } - - /// - /// Represents the smallest possible value of VolumetricHeatCapacity - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static VolumetricHeatCapacity MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the VolumetricHeatCapacity quantity. /// @@ -172,6 +147,9 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -183,12 +161,6 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.VolumetricHeatCapacity; - /// /// The of this quantity. /// @@ -305,7 +277,7 @@ public static string GetAbbreviation(VolumetricHeatCapacityUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(VolumetricHeatCapacityUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -469,7 +441,7 @@ public static VolumetricHeatCapacity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static VolumetricHeatCapacity Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -500,7 +472,7 @@ public static bool TryParse(string? str, out VolumetricHeatCapacity result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out VolumetricHeatCapacity result) { return QuantityParser.Default.TryParse( @@ -528,7 +500,7 @@ public static VolumetricHeatCapacityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -554,7 +526,7 @@ public static bool TryParseUnit(string str, out VolumetricHeatCapacityUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumetricHeatCapacityUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -634,20 +606,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Volum return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(VolumetricHeatCapacity left, VolumetricHeatCapacity right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -663,23 +621,6 @@ public int CompareTo(VolumetricHeatCapacity other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is VolumetricHeatCapacity objVolumetricHeatCapacity)) - return false; - - return Equals(objVolumetricHeatCapacity); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(VolumetricHeatCapacity other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another VolumetricHeatCapacity within the given absolute or relative tolerance. @@ -725,7 +666,7 @@ public bool Equals(VolumetricHeatCapacity other, double tolerance, ComparisonTyp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -751,10 +692,9 @@ public override int GetHashCode() public double As(VolumetricHeatCapacityUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -775,10 +715,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is VolumetricHeatCapacityUnit unitAsVolumetricHeatCapacityUnit)) + if (!(unit is VolumetricHeatCapacityUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); - return As(unitAsVolumetricHeatCapacityUnit); + return (double)As(typedUnit); } /// @@ -867,10 +807,10 @@ private bool TryToUnit(VolumetricHeatCapacityUnit unit, out VolumetricHeatCapaci /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is VolumetricHeatCapacityUnit unitAsVolumetricHeatCapacityUnit)) + 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(unitAsVolumetricHeatCapacityUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -914,63 +854,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -1052,8 +958,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(VolumetricHeatCapacityUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return VolumetricHeatCapacity.QuantityType; else if (conversionType == typeof(QuantityInfo)) return VolumetricHeatCapacity.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index a8a870dd46..b3e92e35dc 100644 --- a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -21,7 +21,6 @@ using System.Globalization; using System.Linq; using System.Runtime.Serialization; -using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -36,7 +35,7 @@ namespace UnitsNet /// A geometric property of an area that is used to determine the warping stress. /// [DataContract] - public readonly partial struct WarpingMomentOfInertia : IQuantity, IEquatable, IComparable, IComparable, IConvertible, IFormattable + public readonly partial struct WarpingMomentOfInertia : IQuantity, IComparable, IComparable, IConvertible, IFormattable { /// /// The numeric value this quantity was constructed with. @@ -54,10 +53,7 @@ static WarpingMomentOfInertia() { BaseDimensions = new BaseDimensions(6, 0, 0, 0, 0, 0, 0); BaseUnit = WarpingMomentOfInertiaUnit.MeterToTheSixth; - MaxValue = new WarpingMomentOfInertia(double.MaxValue, BaseUnit); - MinValue = new WarpingMomentOfInertia(double.MinValue, BaseUnit); - QuantityType = QuantityType.WarpingMomentOfInertia; - Units = Enum.GetValues(typeof(WarpingMomentOfInertiaUnit)).Cast().Except(new WarpingMomentOfInertiaUnit[]{ WarpingMomentOfInertiaUnit.Undefined }).ToArray(); + Units = Enum.GetValues(typeof(WarpingMomentOfInertiaUnit)).Cast().ToArray(); Zero = new WarpingMomentOfInertia(0, BaseUnit); Info = new QuantityInfo("WarpingMomentOfInertia", new UnitInfo[] @@ -69,7 +65,7 @@ static WarpingMomentOfInertia() new UnitInfo(WarpingMomentOfInertiaUnit.MeterToTheSixth, "MetersToTheSixth", new BaseUnits(length: LengthUnit.Meter)), new UnitInfo(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "MillimetersToTheSixth", new BaseUnits(length: LengthUnit.Millimeter)), }, - BaseUnit, Zero, BaseDimensions, QuantityType.WarpingMomentOfInertia); + BaseUnit, Zero, BaseDimensions); DefaultConversionFunctions = new UnitConverter(); RegisterDefaultConversions(DefaultConversionFunctions); @@ -83,9 +79,6 @@ static WarpingMomentOfInertia() /// If value is NaN or Infinity. public WarpingMomentOfInertia(double value, WarpingMomentOfInertiaUnit unit) { - if (unit == WarpingMomentOfInertiaUnit.Undefined) - throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); - _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } @@ -129,24 +122,6 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) /// public static WarpingMomentOfInertiaUnit BaseUnit { get; } - /// - /// Represents the largest possible value of WarpingMomentOfInertia - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static WarpingMomentOfInertia MaxValue { get; } - - /// - /// Represents the smallest possible value of WarpingMomentOfInertia - /// - [Obsolete("MaxValue and MinValue will be removed. Choose your own value or use nullability for unbounded lower/upper range checks. See discussion in https://github.com/angularsen/UnitsNet/issues/848.")] - public static WarpingMomentOfInertia MinValue { get; } - - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public static QuantityType QuantityType { get; } - /// /// All units of measurement for the WarpingMomentOfInertia quantity. /// @@ -166,6 +141,9 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) /// public double Value => _value; + /// + QuantityValue IQuantity.Value => _value; + Enum IQuantity.Unit => Unit; /// @@ -177,12 +155,6 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) /// QuantityInfo IQuantity.QuantityInfo => Info; - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] - public QuantityType Type => QuantityType.WarpingMomentOfInertia; - /// /// The of this quantity. /// @@ -275,7 +247,7 @@ public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit) /// /// Unit to get abbreviation for. /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. + /// Format to use for localization. Defaults to if null. public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); @@ -409,7 +381,7 @@ public static WarpingMomentOfInertia Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static WarpingMomentOfInertia Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse( @@ -440,7 +412,7 @@ public static bool TryParse(string? str, out WarpingMomentOfInertia result) /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse(string? str, IFormatProvider? provider, out WarpingMomentOfInertia result) { return QuantityParser.Default.TryParse( @@ -468,7 +440,7 @@ public static WarpingMomentOfInertiaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -494,7 +466,7 @@ public static bool TryParseUnit(string str, out WarpingMomentOfInertiaUnit unit) /// /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParseUnit(string str, IFormatProvider? provider, out WarpingMomentOfInertiaUnit unit) { return UnitParser.Default.TryParse(str, provider, out unit); @@ -574,20 +546,6 @@ public static bool TryParseUnit(string str, IFormatProvider? provider, out Warpi return left.Value > right.ToUnit(left.Unit).Value; } - /// Returns true if exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator ==(WarpingMomentOfInertia left, WarpingMomentOfInertia right) - { - return left.Equals(right); - } - - /// Returns true if not exactly equal. - /// Consider using for safely comparing floating point values. - public static bool operator !=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) - { - return !(left == right); - } - /// public int CompareTo(object obj) { @@ -603,23 +561,6 @@ public int CompareTo(WarpingMomentOfInertia other) return _value.CompareTo(other.ToUnit(this.Unit).Value); } - /// - /// Consider using for safely comparing floating point values. - public override bool Equals(object obj) - { - if (obj is null || !(obj is WarpingMomentOfInertia objWarpingMomentOfInertia)) - return false; - - return Equals(objWarpingMomentOfInertia); - } - - /// - /// Consider using for safely comparing floating point values. - public bool Equals(WarpingMomentOfInertia other) - { - return _value.Equals(other.ToUnit(this.Unit).Value); - } - /// /// /// Compare equality to another WarpingMomentOfInertia within the given absolute or relative tolerance. @@ -665,7 +606,7 @@ public bool Equals(WarpingMomentOfInertia other, double tolerance, ComparisonTyp if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); - double thisValue = (double)this.Value; + double thisValue = this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); @@ -691,10 +632,9 @@ public override int GetHashCode() public double As(WarpingMomentOfInertiaUnit unit) { if (Unit == unit) - return (double)Value; + return Value; - var converted = ToUnit(unit); - return (double)converted.Value; + return ToUnit(unit).Value; } /// @@ -715,10 +655,10 @@ public double As(UnitSystem unitSystem) /// double IQuantity.As(Enum unit) { - if (!(unit is WarpingMomentOfInertiaUnit unitAsWarpingMomentOfInertiaUnit)) + if (!(unit is WarpingMomentOfInertiaUnit typedUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); - return As(unitAsWarpingMomentOfInertiaUnit); + return (double)As(typedUnit); } /// @@ -801,10 +741,10 @@ private bool TryToUnit(WarpingMomentOfInertiaUnit unit, out WarpingMomentOfInert /// IQuantity IQuantity.ToUnit(Enum unit) { - if (!(unit is WarpingMomentOfInertiaUnit unitAsWarpingMomentOfInertiaUnit)) + 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(unitAsWarpingMomentOfInertiaUnit, DefaultConversionFunctions); + return ToUnit(typedUnit, DefaultConversionFunctions); } /// @@ -848,63 +788,29 @@ public override string ToString() /// Gets the default string representation of value and unit using the given format provider. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. public string ToString(IFormatProvider? provider) { return ToString("g", provider); } - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) - { - var value = Convert.ToDouble(Value); - var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(provider, format); - } - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - if (args == null) throw new ArgumentNullException(nameof(args)); - - provider = provider ?? CultureInfo.CurrentUICulture; - - var value = Convert.ToDouble(Value); - var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); - return string.Format(provider, format, formatArgs); - } - /// /// - /// Gets the string representation of this instance in the specified format string using . + /// Gets the string representation of this instance in the specified format string using . /// /// The format string. /// The string representation. public string ToString(string format) { - return ToString(format, CultureInfo.CurrentUICulture); + return ToString(format, CultureInfo.CurrentCulture); } /// /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. + /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. /// The string representation. public string ToString(string format, IFormatProvider? provider) { @@ -986,8 +892,6 @@ object IConvertible.ToType(Type conversionType, IFormatProvider provider) return this; else if (conversionType == typeof(WarpingMomentOfInertiaUnit)) return Unit; - else if (conversionType == typeof(QuantityType)) - return WarpingMomentOfInertia.QuantityType; else if (conversionType == typeof(QuantityInfo)) return WarpingMomentOfInertia.Info; else if (conversionType == typeof(BaseDimensions)) diff --git a/UnitsNet/GeneratedCode/Quantity.g.cs b/UnitsNet/GeneratedCode/Quantity.g.cs index 23fe874139..10e0037d7c 100644 --- a/UnitsNet/GeneratedCode/Quantity.g.cs +++ b/UnitsNet/GeneratedCode/Quantity.g.cs @@ -19,8 +19,6 @@ using System; using System.Globalization; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; using UnitsNet.Units; using System.Collections.Generic; @@ -157,138 +155,6 @@ public static partial class Quantity { "WarpingMomentOfInertia", WarpingMomentOfInertia.Info }, }; - /// - /// Dynamically constructs a quantity of the given with the value in the quantity's base units. - /// - /// The of the quantity to create. - /// The value to construct the quantity with. - /// The created quantity. - [Obsolete("QuantityType will be removed. Use FromQuantityInfo(QuantityInfo, QuantityValue) instead.")] - public static IQuantity FromQuantityType(QuantityType quantityType, QuantityValue value) - { - return quantityType switch - { - QuantityType.Acceleration => Acceleration.From(value, Acceleration.BaseUnit), - QuantityType.AmountOfSubstance => AmountOfSubstance.From(value, AmountOfSubstance.BaseUnit), - QuantityType.AmplitudeRatio => AmplitudeRatio.From(value, AmplitudeRatio.BaseUnit), - QuantityType.Angle => Angle.From(value, Angle.BaseUnit), - QuantityType.ApparentEnergy => ApparentEnergy.From(value, ApparentEnergy.BaseUnit), - QuantityType.ApparentPower => ApparentPower.From(value, ApparentPower.BaseUnit), - QuantityType.Area => Area.From(value, Area.BaseUnit), - QuantityType.AreaDensity => AreaDensity.From(value, AreaDensity.BaseUnit), - QuantityType.AreaMomentOfInertia => AreaMomentOfInertia.From(value, AreaMomentOfInertia.BaseUnit), - QuantityType.BitRate => BitRate.From(value, BitRate.BaseUnit), - QuantityType.BrakeSpecificFuelConsumption => BrakeSpecificFuelConsumption.From(value, BrakeSpecificFuelConsumption.BaseUnit), - QuantityType.Capacitance => Capacitance.From(value, Capacitance.BaseUnit), - QuantityType.CoefficientOfThermalExpansion => CoefficientOfThermalExpansion.From(value, CoefficientOfThermalExpansion.BaseUnit), - QuantityType.Compressibility => Compressibility.From(value, Compressibility.BaseUnit), - QuantityType.Density => Density.From(value, Density.BaseUnit), - QuantityType.Duration => Duration.From(value, Duration.BaseUnit), - QuantityType.DynamicViscosity => DynamicViscosity.From(value, DynamicViscosity.BaseUnit), - QuantityType.ElectricAdmittance => ElectricAdmittance.From(value, ElectricAdmittance.BaseUnit), - QuantityType.ElectricCharge => ElectricCharge.From(value, ElectricCharge.BaseUnit), - QuantityType.ElectricChargeDensity => ElectricChargeDensity.From(value, ElectricChargeDensity.BaseUnit), - QuantityType.ElectricConductance => ElectricConductance.From(value, ElectricConductance.BaseUnit), - QuantityType.ElectricConductivity => ElectricConductivity.From(value, ElectricConductivity.BaseUnit), - QuantityType.ElectricCurrent => ElectricCurrent.From(value, ElectricCurrent.BaseUnit), - QuantityType.ElectricCurrentDensity => ElectricCurrentDensity.From(value, ElectricCurrentDensity.BaseUnit), - QuantityType.ElectricCurrentGradient => ElectricCurrentGradient.From(value, ElectricCurrentGradient.BaseUnit), - QuantityType.ElectricField => ElectricField.From(value, ElectricField.BaseUnit), - QuantityType.ElectricInductance => ElectricInductance.From(value, ElectricInductance.BaseUnit), - QuantityType.ElectricPotential => ElectricPotential.From(value, ElectricPotential.BaseUnit), - QuantityType.ElectricPotentialAc => ElectricPotentialAc.From(value, ElectricPotentialAc.BaseUnit), - QuantityType.ElectricPotentialChangeRate => ElectricPotentialChangeRate.From(value, ElectricPotentialChangeRate.BaseUnit), - QuantityType.ElectricPotentialDc => ElectricPotentialDc.From(value, ElectricPotentialDc.BaseUnit), - QuantityType.ElectricResistance => ElectricResistance.From(value, ElectricResistance.BaseUnit), - QuantityType.ElectricResistivity => ElectricResistivity.From(value, ElectricResistivity.BaseUnit), - QuantityType.ElectricSurfaceChargeDensity => ElectricSurfaceChargeDensity.From(value, ElectricSurfaceChargeDensity.BaseUnit), - QuantityType.Energy => Energy.From(value, Energy.BaseUnit), - QuantityType.EnergyDensity => EnergyDensity.From(value, EnergyDensity.BaseUnit), - QuantityType.Entropy => Entropy.From(value, Entropy.BaseUnit), - QuantityType.Force => Force.From(value, Force.BaseUnit), - QuantityType.ForceChangeRate => ForceChangeRate.From(value, ForceChangeRate.BaseUnit), - QuantityType.ForcePerLength => ForcePerLength.From(value, ForcePerLength.BaseUnit), - QuantityType.Frequency => Frequency.From(value, Frequency.BaseUnit), - QuantityType.FuelEfficiency => FuelEfficiency.From(value, FuelEfficiency.BaseUnit), - QuantityType.HeatFlux => HeatFlux.From(value, HeatFlux.BaseUnit), - QuantityType.HeatTransferCoefficient => HeatTransferCoefficient.From(value, HeatTransferCoefficient.BaseUnit), - QuantityType.Illuminance => Illuminance.From(value, Illuminance.BaseUnit), - QuantityType.Information => Information.From(value, Information.BaseUnit), - QuantityType.Irradiance => Irradiance.From(value, Irradiance.BaseUnit), - QuantityType.Irradiation => Irradiation.From(value, Irradiation.BaseUnit), - QuantityType.Jerk => Jerk.From(value, Jerk.BaseUnit), - QuantityType.KinematicViscosity => KinematicViscosity.From(value, KinematicViscosity.BaseUnit), - QuantityType.LapseRate => LapseRate.From(value, LapseRate.BaseUnit), - QuantityType.Length => Length.From(value, Length.BaseUnit), - QuantityType.Level => Level.From(value, Level.BaseUnit), - QuantityType.LinearDensity => LinearDensity.From(value, LinearDensity.BaseUnit), - QuantityType.LinearPowerDensity => LinearPowerDensity.From(value, LinearPowerDensity.BaseUnit), - QuantityType.Luminance => Luminance.From(value, Luminance.BaseUnit), - QuantityType.Luminosity => Luminosity.From(value, Luminosity.BaseUnit), - QuantityType.LuminousFlux => LuminousFlux.From(value, LuminousFlux.BaseUnit), - QuantityType.LuminousIntensity => LuminousIntensity.From(value, LuminousIntensity.BaseUnit), - QuantityType.MagneticField => MagneticField.From(value, MagneticField.BaseUnit), - QuantityType.MagneticFlux => MagneticFlux.From(value, MagneticFlux.BaseUnit), - QuantityType.Magnetization => Magnetization.From(value, Magnetization.BaseUnit), - QuantityType.Mass => Mass.From(value, Mass.BaseUnit), - QuantityType.MassConcentration => MassConcentration.From(value, MassConcentration.BaseUnit), - QuantityType.MassFlow => MassFlow.From(value, MassFlow.BaseUnit), - QuantityType.MassFlux => MassFlux.From(value, MassFlux.BaseUnit), - QuantityType.MassFraction => MassFraction.From(value, MassFraction.BaseUnit), - QuantityType.MassMomentOfInertia => MassMomentOfInertia.From(value, MassMomentOfInertia.BaseUnit), - QuantityType.MolarEnergy => MolarEnergy.From(value, MolarEnergy.BaseUnit), - QuantityType.MolarEntropy => MolarEntropy.From(value, MolarEntropy.BaseUnit), - QuantityType.Molarity => Molarity.From(value, Molarity.BaseUnit), - QuantityType.MolarMass => MolarMass.From(value, MolarMass.BaseUnit), - QuantityType.Permeability => Permeability.From(value, Permeability.BaseUnit), - QuantityType.Permittivity => Permittivity.From(value, Permittivity.BaseUnit), - QuantityType.PorousMediumPermeability => PorousMediumPermeability.From(value, PorousMediumPermeability.BaseUnit), - QuantityType.Power => Power.From(value, Power.BaseUnit), - QuantityType.PowerDensity => PowerDensity.From(value, PowerDensity.BaseUnit), - QuantityType.PowerRatio => PowerRatio.From(value, PowerRatio.BaseUnit), - QuantityType.Pressure => Pressure.From(value, Pressure.BaseUnit), - QuantityType.PressureChangeRate => PressureChangeRate.From(value, PressureChangeRate.BaseUnit), - QuantityType.Ratio => Ratio.From(value, Ratio.BaseUnit), - QuantityType.RatioChangeRate => RatioChangeRate.From(value, RatioChangeRate.BaseUnit), - QuantityType.ReactiveEnergy => ReactiveEnergy.From(value, ReactiveEnergy.BaseUnit), - QuantityType.ReactivePower => ReactivePower.From(value, ReactivePower.BaseUnit), - QuantityType.ReciprocalArea => ReciprocalArea.From(value, ReciprocalArea.BaseUnit), - QuantityType.ReciprocalLength => ReciprocalLength.From(value, ReciprocalLength.BaseUnit), - QuantityType.RelativeHumidity => RelativeHumidity.From(value, RelativeHumidity.BaseUnit), - QuantityType.RotationalAcceleration => RotationalAcceleration.From(value, RotationalAcceleration.BaseUnit), - QuantityType.RotationalSpeed => RotationalSpeed.From(value, RotationalSpeed.BaseUnit), - QuantityType.RotationalStiffness => RotationalStiffness.From(value, RotationalStiffness.BaseUnit), - QuantityType.RotationalStiffnessPerLength => RotationalStiffnessPerLength.From(value, RotationalStiffnessPerLength.BaseUnit), - QuantityType.Scalar => Scalar.From(value, Scalar.BaseUnit), - QuantityType.SolidAngle => SolidAngle.From(value, SolidAngle.BaseUnit), - QuantityType.SpecificEnergy => SpecificEnergy.From(value, SpecificEnergy.BaseUnit), - QuantityType.SpecificEntropy => SpecificEntropy.From(value, SpecificEntropy.BaseUnit), - QuantityType.SpecificFuelConsumption => SpecificFuelConsumption.From(value, SpecificFuelConsumption.BaseUnit), - QuantityType.SpecificVolume => SpecificVolume.From(value, SpecificVolume.BaseUnit), - QuantityType.SpecificWeight => SpecificWeight.From(value, SpecificWeight.BaseUnit), - QuantityType.Speed => Speed.From(value, Speed.BaseUnit), - QuantityType.StandardVolumeFlow => StandardVolumeFlow.From(value, StandardVolumeFlow.BaseUnit), - QuantityType.Temperature => Temperature.From(value, Temperature.BaseUnit), - QuantityType.TemperatureChangeRate => TemperatureChangeRate.From(value, TemperatureChangeRate.BaseUnit), - QuantityType.TemperatureDelta => TemperatureDelta.From(value, TemperatureDelta.BaseUnit), - QuantityType.TemperatureGradient => TemperatureGradient.From(value, TemperatureGradient.BaseUnit), - QuantityType.ThermalConductivity => ThermalConductivity.From(value, ThermalConductivity.BaseUnit), - QuantityType.ThermalResistance => ThermalResistance.From(value, ThermalResistance.BaseUnit), - QuantityType.Torque => Torque.From(value, Torque.BaseUnit), - QuantityType.TorquePerLength => TorquePerLength.From(value, TorquePerLength.BaseUnit), - QuantityType.Turbidity => Turbidity.From(value, Turbidity.BaseUnit), - QuantityType.VitaminA => VitaminA.From(value, VitaminA.BaseUnit), - QuantityType.Volume => Volume.From(value, Volume.BaseUnit), - QuantityType.VolumeConcentration => VolumeConcentration.From(value, VolumeConcentration.BaseUnit), - QuantityType.VolumeFlow => VolumeFlow.From(value, VolumeFlow.BaseUnit), - QuantityType.VolumeFlowPerArea => VolumeFlowPerArea.From(value, VolumeFlowPerArea.BaseUnit), - QuantityType.VolumePerLength => VolumePerLength.From(value, VolumePerLength.BaseUnit), - QuantityType.VolumetricHeatCapacity => VolumetricHeatCapacity.From(value, VolumetricHeatCapacity.BaseUnit), - QuantityType.WarpingMomentOfInertia => WarpingMomentOfInertia.From(value, WarpingMomentOfInertia.BaseUnit), - _ => throw new ArgumentException($"{quantityType} is not a supported quantity type.") - }; - } - /// /// Dynamically constructs a quantity of the given with the value in the quantity's base units. /// @@ -418,7 +284,7 @@ public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, QuantityValu "WarpingMomentOfInertia" => WarpingMomentOfInertia.From(value, WarpingMomentOfInertia.BaseUnit), _ => throw new ArgumentException($"{quantityInfo.Name} is not a supported quantity.") }; - } + } /// /// Try to dynamically construct a quantity. @@ -793,7 +659,7 @@ public static bool TryFrom(QuantityValue value, Enum unit, out IQuantity? quanti /// /// Try to dynamically parse a quantity string representation. /// - /// The format provider to use for lookup. Defaults to if null. + /// The format provider to use for lookup. Defaults to if null. /// Type of quantity, such as . /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. /// The resulting quantity if successful, otherwise default. @@ -802,7 +668,7 @@ public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, { quantity = default(IQuantity); - if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) + if (!typeof(IQuantity).IsAssignableFrom(quantityType)) return false; var parser = QuantityParser.Default; @@ -928,7 +794,7 @@ public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, Type _ when quantityType == typeof(WarpingMomentOfInertia) => parser.TryParse(quantityString, formatProvider, WarpingMomentOfInertia.From, out quantity), _ => false }; - } + } internal static IEnumerable GetQuantityTypes() { diff --git a/UnitsNet/GeneratedCode/QuantityType.g.cs b/UnitsNet/GeneratedCode/QuantityType.g.cs deleted file mode 100644 index c18ccdf35e..0000000000 --- a/UnitsNet/GeneratedCode/QuantityType.g.cs +++ /dev/null @@ -1,158 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by \generate-code.bat. -// -// Changes to this file will be lost when the code is regenerated. -// The build server regenerates the code before each build and a pre-build -// step will regenerate the code on each local build. -// -// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. -// -// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. -// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. -// -// -//------------------------------------------------------------------------------ - -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -// ReSharper disable once CheckNamespace - -using System; - -namespace UnitsNet -{ - /// - /// Lists all generated quantities with the same name as the quantity struct type, - /// such as Length, Mass, Force etc. - /// This is useful for populating options in the UI, such as creating a generic conversion - /// tool with inputValue, quantityName, fromUnit and toUnit selectors. - /// - [Obsolete("QuantityType will be removed in the future. Use the QuantityInfo class instead.")] - public enum QuantityType - { -// Missing XML comment for public type or member -#pragma warning disable CS1591 - Undefined = 0, - Acceleration, - AmountOfSubstance, - AmplitudeRatio, - Angle, - ApparentEnergy, - ApparentPower, - Area, - AreaDensity, - AreaMomentOfInertia, - BitRate, - BrakeSpecificFuelConsumption, - Capacitance, - CoefficientOfThermalExpansion, - Compressibility, - Density, - Duration, - DynamicViscosity, - ElectricAdmittance, - ElectricCharge, - ElectricChargeDensity, - ElectricConductance, - ElectricConductivity, - ElectricCurrent, - ElectricCurrentDensity, - ElectricCurrentGradient, - ElectricField, - ElectricInductance, - ElectricPotential, - ElectricPotentialAc, - ElectricPotentialChangeRate, - ElectricPotentialDc, - ElectricResistance, - ElectricResistivity, - ElectricSurfaceChargeDensity, - Energy, - EnergyDensity, - Entropy, - Force, - ForceChangeRate, - ForcePerLength, - Frequency, - FuelEfficiency, - HeatFlux, - HeatTransferCoefficient, - Illuminance, - Information, - Irradiance, - Irradiation, - Jerk, - KinematicViscosity, - LapseRate, - Length, - Level, - LinearDensity, - LinearPowerDensity, - Luminance, - Luminosity, - LuminousFlux, - LuminousIntensity, - MagneticField, - MagneticFlux, - Magnetization, - Mass, - MassConcentration, - MassFlow, - MassFlux, - MassFraction, - MassMomentOfInertia, - MolarEnergy, - MolarEntropy, - Molarity, - MolarMass, - Permeability, - Permittivity, - PorousMediumPermeability, - Power, - PowerDensity, - PowerRatio, - Pressure, - PressureChangeRate, - Ratio, - RatioChangeRate, - ReactiveEnergy, - ReactivePower, - ReciprocalArea, - ReciprocalLength, - RelativeHumidity, - RotationalAcceleration, - RotationalSpeed, - RotationalStiffness, - RotationalStiffnessPerLength, - Scalar, - SolidAngle, - SpecificEnergy, - SpecificEntropy, - SpecificFuelConsumption, - SpecificVolume, - SpecificWeight, - Speed, - StandardVolumeFlow, - Temperature, - TemperatureChangeRate, - TemperatureDelta, - TemperatureGradient, - ThermalConductivity, - ThermalResistance, - Torque, - TorquePerLength, - Turbidity, - VitaminA, - Volume, - VolumeConcentration, - VolumeFlow, - VolumeFlowPerArea, - VolumePerLength, - VolumetricHeatCapacity, - WarpingMomentOfInertia, -// Missing XML comment for public type or member -#pragma warning restore CS1591 - } -} diff --git a/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs b/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs index 46b76aa052..b4f1c48938 100644 --- a/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AccelerationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AccelerationUnit { - Undefined = 0, CentimeterPerSecondSquared = 1, DecimeterPerSecondSquared = 2, FootPerSecondSquared = 3, diff --git a/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs index 0c60a66ce4..e0ce7a5da7 100644 --- a/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AmountOfSubstanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AmountOfSubstanceUnit { - Undefined = 0, Centimole = 1, CentipoundMole = 2, Decimole = 3, diff --git a/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs b/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs index 1e2c42e1c7..97a8d592f6 100644 --- a/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AmplitudeRatioUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AmplitudeRatioUnit { - Undefined = 0, DecibelMicrovolt = 1, DecibelMillivolt = 2, DecibelUnloaded = 3, diff --git a/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs b/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs index e506e802d2..20e4ff440e 100644 --- a/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AngleUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AngleUnit { - Undefined = 0, Arcminute = 1, Arcsecond = 2, Centiradian = 3, diff --git a/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs index f070ab2cb8..2a8c1aba5b 100644 --- a/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ApparentEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ApparentEnergyUnit { - Undefined = 0, KilovoltampereHour = 1, MegavoltampereHour = 2, VoltampereHour = 3, diff --git a/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs b/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs index 1167dda66c..358388af5f 100644 --- a/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ApparentPowerUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ApparentPowerUnit { - Undefined = 0, Gigavoltampere = 1, Kilovoltampere = 2, Megavoltampere = 3, diff --git a/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs index 053acbdc48..bacdc7e8f4 100644 --- a/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AreaDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AreaDensityUnit { - Undefined = 0, /// /// Also known as grammage for paper industry. In fiber industry used with abbreviation 'gsm'. diff --git a/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs b/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs index 554a32a8fa..388a130b9d 100644 --- a/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AreaMomentOfInertiaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AreaMomentOfInertiaUnit { - Undefined = 0, CentimeterToTheFourth = 1, DecimeterToTheFourth = 2, FootToTheFourth = 3, diff --git a/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs b/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs index 55077cf9a9..f0320c4e99 100644 --- a/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/AreaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum AreaUnit { - Undefined = 0, Acre = 1, Hectare = 2, SquareCentimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs index 2390d38afa..6a3760ef6b 100644 --- a/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/BitRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum BitRateUnit { - Undefined = 0, BitPerSecond = 1, BytePerSecond = 2, ExabitPerSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs b/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs index cd1f6a61fb..73c93e2039 100644 --- a/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/BrakeSpecificFuelConsumptionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum BrakeSpecificFuelConsumptionUnit { - Undefined = 0, GramPerKiloWattHour = 1, KilogramPerJoule = 2, diff --git a/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs index feaebb42fe..a76cc8f2d8 100644 --- a/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/CapacitanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum CapacitanceUnit { - Undefined = 0, Farad = 1, Kilofarad = 2, Megafarad = 3, diff --git a/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs b/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs index eb54f874c2..9b7c73ef86 100644 --- a/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/CoefficientOfThermalExpansionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum CoefficientOfThermalExpansionUnit { - Undefined = 0, InverseDegreeCelsius = 1, InverseDegreeFahrenheit = 2, InverseKelvin = 3, diff --git a/UnitsNet/GeneratedCode/Units/CompressibilityUnit.g.cs b/UnitsNet/GeneratedCode/Units/CompressibilityUnit.g.cs index a45732e3b2..c272160cf2 100644 --- a/UnitsNet/GeneratedCode/Units/CompressibilityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/CompressibilityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum CompressibilityUnit { - Undefined = 0, InverseAtmosphere = 1, InverseBar = 2, InverseKilopascal = 3, diff --git a/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs index f6bdef8d33..a1c2aaa2d3 100644 --- a/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/DensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum DensityUnit { - Undefined = 0, CentigramPerDeciliter = 1, CentigramPerLiter = 2, CentigramPerMilliliter = 3, diff --git a/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs b/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs index a328323136..6c6aab7c78 100644 --- a/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/DurationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum DurationUnit { - Undefined = 0, Day = 1, Hour = 2, JulianYear = 3, diff --git a/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs b/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs index 9d1a1cde30..607837db48 100644 --- a/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/DynamicViscosityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum DynamicViscosityUnit { - Undefined = 0, Centipoise = 1, MicropascalSecond = 2, MillipascalSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs index b0e4153a7e..622b45de43 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricAdmittanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricAdmittanceUnit { - Undefined = 0, Microsiemens = 1, Millisiemens = 2, Nanosiemens = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs index 0ebcd43c0f..05909c9a62 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricChargeDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricChargeDensityUnit { - Undefined = 0, CoulombPerCubicMeter = 1, } diff --git a/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs index 7f9ef9b551..4fda90bf6f 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricChargeUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricChargeUnit { - Undefined = 0, AmpereHour = 1, Coulomb = 2, KiloampereHour = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs index a02ff6fa3a..7bd2b92711 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricConductanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricConductanceUnit { - Undefined = 0, Microsiemens = 1, Millisiemens = 2, Siemens = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs index 509168d9fd..3bca9b88e6 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricConductivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricConductivityUnit { - Undefined = 0, MicrosiemensPerCentimeter = 6, MillisiemensPerCentimeter = 12, SiemensPerCentimeter = 13, diff --git a/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs index 850c97a9af..433e70c970 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricCurrentDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricCurrentDensityUnit { - Undefined = 0, AmperePerSquareFoot = 1, AmperePerSquareInch = 2, AmperePerSquareMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs index f6ab790687..eb247e6cfc 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricCurrentGradientUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricCurrentGradientUnit { - Undefined = 0, AmperePerMicrosecond = 1, AmperePerMillisecond = 2, AmperePerNanosecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs index fd5b0f23f5..8ddd75ca00 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricCurrentUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricCurrentUnit { - Undefined = 0, Ampere = 1, Centiampere = 2, Kiloampere = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs index 2aa0e2989f..03ac0494d0 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricFieldUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricFieldUnit { - Undefined = 0, VoltPerMeter = 1, } diff --git a/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs index 41e2121f34..38e85791db 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricInductanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricInductanceUnit { - Undefined = 0, Henry = 1, Microhenry = 2, Millihenry = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs index bdb5086350..ada8068172 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialAcUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialAcUnit { - Undefined = 0, KilovoltAc = 1, MegavoltAc = 2, MicrovoltAc = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs index 3f634b07bf..cac18f9c78 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialChangeRateUnit { - Undefined = 0, KilovoltPerHour = 1, KilovoltPerMicrosecond = 2, KilovoltPerMinute = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs index 05fb4fdd53..224c9c4c30 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialDcUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialDcUnit { - Undefined = 0, KilovoltDc = 1, MegavoltDc = 2, MicrovoltDc = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs index 6540697325..187e8bb192 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricPotentialUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricPotentialUnit { - Undefined = 0, Kilovolt = 1, Megavolt = 2, Microvolt = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs index 31c307e4b6..3852120742 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricResistanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricResistanceUnit { - Undefined = 0, Gigaohm = 1, Kiloohm = 2, Megaohm = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs index 2408b4c477..c7f43cfc6c 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricResistivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricResistivityUnit { - Undefined = 0, KiloohmCentimeter = 1, KiloohmMeter = 2, MegaohmCentimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs index 7fc4d00624..30c7a098de 100644 --- a/UnitsNet/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ElectricSurfaceChargeDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ElectricSurfaceChargeDensityUnit { - Undefined = 0, CoulombPerSquareCentimeter = 1, CoulombPerSquareInch = 2, CoulombPerSquareMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/EnergyDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/EnergyDensityUnit.g.cs index b460210e4b..bf72f7d4f3 100644 --- a/UnitsNet/GeneratedCode/Units/EnergyDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/EnergyDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum EnergyDensityUnit { - Undefined = 0, GigajoulePerCubicMeter = 6, GigawattHourPerCubicMeter = 8, JoulePerCubicMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs index c456440c83..2e8dd78935 100644 --- a/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/EnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum EnergyUnit { - Undefined = 0, BritishThermalUnit = 1, Calorie = 2, DecathermEc = 3, diff --git a/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs b/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs index b344a123b0..1fbd647e03 100644 --- a/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/EntropyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum EntropyUnit { - Undefined = 0, CaloriePerKelvin = 1, JoulePerDegreeCelsius = 2, JoulePerKelvin = 3, diff --git a/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs index b45d8f37bf..9b76b2f23a 100644 --- a/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ForceChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ForceChangeRateUnit { - Undefined = 0, CentinewtonPerSecond = 1, DecanewtonPerMinute = 2, DecanewtonPerSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs index 198215708c..7f6a376ca3 100644 --- a/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ForcePerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ForcePerLengthUnit { - Undefined = 0, CentinewtonPerCentimeter = 1, CentinewtonPerMeter = 2, CentinewtonPerMillimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs index ace80b3d9f..107e6ae7e4 100644 --- a/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ForceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ForceUnit { - Undefined = 0, Decanewton = 1, Dyn = 2, KilogramForce = 3, diff --git a/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs b/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs index 937416774a..c78283ce9c 100644 --- a/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/FrequencyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum FrequencyUnit { - Undefined = 0, BeatPerMinute = 1, BUnit = 2, CyclePerHour = 3, diff --git a/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.g.cs b/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.g.cs index 603d4f60c4..24491dee95 100644 --- a/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/FuelEfficiencyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum FuelEfficiencyUnit { - Undefined = 0, KilometerPerLiter = 1, LiterPer100Kilometers = 2, MilePerUkGallon = 3, diff --git a/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs index 343ac00a17..a03b4d90e6 100644 --- a/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/HeatFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum HeatFluxUnit { - Undefined = 0, BtuPerHourSquareFoot = 1, BtuPerMinuteSquareFoot = 2, BtuPerSecondSquareFoot = 3, diff --git a/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs b/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs index 612f5fd15d..e337b5095a 100644 --- a/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/HeatTransferCoefficientUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum HeatTransferCoefficientUnit { - Undefined = 0, BtuPerSquareFootDegreeFahrenheit = 1, WattPerSquareMeterCelsius = 2, WattPerSquareMeterKelvin = 3, diff --git a/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs index 2884dbc49f..7675a53867 100644 --- a/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/IlluminanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum IlluminanceUnit { - Undefined = 0, Kilolux = 1, Lux = 2, Megalux = 3, diff --git a/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs b/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs index c9f39a1851..fd72b621c2 100644 --- a/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/InformationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum InformationUnit { - Undefined = 0, Bit = 1, Byte = 2, Exabit = 3, diff --git a/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs b/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs index 953dc136c2..2ed5f09b06 100644 --- a/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/IrradianceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum IrradianceUnit { - Undefined = 0, KilowattPerSquareCentimeter = 1, KilowattPerSquareMeter = 2, MegawattPerSquareCentimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs b/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs index a3890297b3..449fdf2491 100644 --- a/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/IrradiationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum IrradiationUnit { - Undefined = 0, JoulePerSquareCentimeter = 1, JoulePerSquareMeter = 2, JoulePerSquareMillimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/JerkUnit.g.cs b/UnitsNet/GeneratedCode/Units/JerkUnit.g.cs index 1c33b996c1..e269a35497 100644 --- a/UnitsNet/GeneratedCode/Units/JerkUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/JerkUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum JerkUnit { - Undefined = 0, CentimeterPerSecondCubed = 1, DecimeterPerSecondCubed = 2, FootPerSecondCubed = 3, diff --git a/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs b/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs index a834ca556c..f01709d0c3 100644 --- a/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/KinematicViscosityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum KinematicViscosityUnit { - Undefined = 0, Centistokes = 1, Decistokes = 2, Kilostokes = 3, diff --git a/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs index cdc802a5fe..b6be109fd4 100644 --- a/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LapseRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LapseRateUnit { - Undefined = 0, DegreeCelsiusPerKilometer = 1, } diff --git a/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs index 613a0a4f54..3c8459608b 100644 --- a/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LengthUnit { - Undefined = 0, /// /// Angstrom is a metric unit of length equal to 1e-10 meter diff --git a/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs b/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs index 7ae6a7f7b3..3d1966d2b2 100644 --- a/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LevelUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LevelUnit { - Undefined = 0, Decibel = 1, Neper = 2, } diff --git a/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs index e2135b4248..652bf6b524 100644 --- a/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LinearDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LinearDensityUnit { - Undefined = 0, GramPerCentimeter = 1, GramPerMeter = 2, GramPerMillimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/LinearPowerDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/LinearPowerDensityUnit.g.cs index a75b9242b3..2ab6e250ac 100644 --- a/UnitsNet/GeneratedCode/Units/LinearPowerDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LinearPowerDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LinearPowerDensityUnit { - Undefined = 0, GigawattPerCentimeter = 1, GigawattPerFoot = 2, GigawattPerInch = 3, diff --git a/UnitsNet/GeneratedCode/Units/LuminanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/LuminanceUnit.g.cs index 0bb831b042..24814e4dcc 100644 --- a/UnitsNet/GeneratedCode/Units/LuminanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LuminanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminanceUnit { - Undefined = 0, CandelaPerSquareFoot = 10, CandelaPerSquareInch = 7, CandelaPerSquareMeter = 8, diff --git a/UnitsNet/GeneratedCode/Units/LuminosityUnit.g.cs b/UnitsNet/GeneratedCode/Units/LuminosityUnit.g.cs index e67ff7eaf2..44cdfec58c 100644 --- a/UnitsNet/GeneratedCode/Units/LuminosityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LuminosityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminosityUnit { - Undefined = 0, Decawatt = 1, Deciwatt = 2, Femtowatt = 3, diff --git a/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs index 1feaa278db..01a956a02c 100644 --- a/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LuminousFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminousFluxUnit { - Undefined = 0, Lumen = 1, } diff --git a/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs index a274ff66bb..947d36fb22 100644 --- a/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum LuminousIntensityUnit { - Undefined = 0, Candela = 1, } diff --git a/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs b/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs index fea90267d8..3915ff523d 100644 --- a/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MagneticFieldUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MagneticFieldUnit { - Undefined = 0, Gauss = 1, Microtesla = 2, Milligauss = 3, diff --git a/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs index 01b2a98881..e7f3635d2e 100644 --- a/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MagneticFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MagneticFluxUnit { - Undefined = 0, Weber = 1, } diff --git a/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs b/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs index b0cad1d3ee..956c88e2da 100644 --- a/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MagnetizationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MagnetizationUnit { - Undefined = 0, AmperePerMeter = 1, } diff --git a/UnitsNet/GeneratedCode/Units/MassConcentrationUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassConcentrationUnit.g.cs index 300abb73f1..e80ca6a945 100644 --- a/UnitsNet/GeneratedCode/Units/MassConcentrationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassConcentrationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassConcentrationUnit { - Undefined = 0, CentigramPerDeciliter = 1, CentigramPerLiter = 2, CentigramPerMicroliter = 3, diff --git a/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs index 05e7a1bda4..7df77cf7b5 100644 --- a/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassFlowUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassFlowUnit { - Undefined = 0, CentigramPerDay = 1, CentigramPerSecond = 2, DecagramPerDay = 3, diff --git a/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs index 35e800eb11..def9d86acb 100644 --- a/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassFluxUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassFluxUnit { - Undefined = 0, GramPerHourPerSquareCentimeter = 1, GramPerHourPerSquareMeter = 2, GramPerHourPerSquareMillimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/MassFractionUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassFractionUnit.g.cs index f739fe0ed9..0dad8a059f 100644 --- a/UnitsNet/GeneratedCode/Units/MassFractionUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassFractionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassFractionUnit { - Undefined = 0, CentigramPerGram = 1, CentigramPerKilogram = 2, DecagramPerGram = 3, diff --git a/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs index 7fac42d9f7..33c92670cb 100644 --- a/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassMomentOfInertiaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassMomentOfInertiaUnit { - Undefined = 0, GramSquareCentimeter = 1, GramSquareDecimeter = 2, GramSquareMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/MassUnit.g.cs b/UnitsNet/GeneratedCode/Units/MassUnit.g.cs index b88ff4ffea..5cf1e962b4 100644 --- a/UnitsNet/GeneratedCode/Units/MassUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MassUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MassUnit { - Undefined = 0, Centigram = 1, Decagram = 2, Decigram = 3, diff --git a/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs index 71c6f75ae5..71772f28ea 100644 --- a/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarEnergyUnit { - Undefined = 0, JoulePerMole = 1, KilojoulePerMole = 2, MegajoulePerMole = 3, diff --git a/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs index d0db13e9e6..b7e6c5aa56 100644 --- a/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarEntropyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarEntropyUnit { - Undefined = 0, JoulePerMoleKelvin = 1, KilojoulePerMoleKelvin = 2, MegajoulePerMoleKelvin = 3, diff --git a/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs index 11fa8ae422..417075c855 100644 --- a/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarMassUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarMassUnit { - Undefined = 0, CentigramPerMole = 1, DecagramPerMole = 2, DecigramPerMole = 3, diff --git a/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs b/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs index 0ece495fca..3d914b3836 100644 --- a/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/MolarityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum MolarityUnit { - Undefined = 0, CentimolePerLiter = 1, [System.Obsolete("Use the singular unit instead.")] CentimolesPerLiter = 2, diff --git a/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs index 0201d80052..19860cb22a 100644 --- a/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PermeabilityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PermeabilityUnit { - Undefined = 0, HenryPerMeter = 1, } diff --git a/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs index 1409a5302a..77e869b6fe 100644 --- a/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PermittivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PermittivityUnit { - Undefined = 0, FaradPerMeter = 1, } diff --git a/UnitsNet/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs index a50e0e2309..9b57db7199 100644 --- a/UnitsNet/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PorousMediumPermeabilityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PorousMediumPermeabilityUnit { - Undefined = 0, Darcy = 1, Microdarcy = 2, Millidarcy = 3, diff --git a/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs b/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs index 8ee2c0fdf2..74a52d1da5 100644 --- a/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PowerDensityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PowerDensityUnit { - Undefined = 0, DecawattPerCubicFoot = 1, DecawattPerCubicInch = 2, DecawattPerCubicMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs b/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs index cb3e453996..f0c4dc508c 100644 --- a/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PowerRatioUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PowerRatioUnit { - Undefined = 0, DecibelMilliwatt = 1, DecibelWatt = 2, } diff --git a/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs b/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs index 6cbbd7bea0..303f690f6e 100644 --- a/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PowerUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PowerUnit { - Undefined = 0, BoilerHorsepower = 1, BritishThermalUnitPerHour = 2, Decawatt = 3, diff --git a/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs index da273f2fba..fed99a6a4a 100644 --- a/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PressureChangeRateUnit { - Undefined = 0, AtmospherePerSecond = 1, KilopascalPerMinute = 2, KilopascalPerSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs index 49d9287d09..5d832b88b1 100644 --- a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum PressureUnit { - Undefined = 0, Atmosphere = 1, Bar = 2, Centibar = 3, diff --git a/UnitsNet/GeneratedCode/Units/RatioChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/RatioChangeRateUnit.g.cs index 56b777fd88..8537a14a05 100644 --- a/UnitsNet/GeneratedCode/Units/RatioChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RatioChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RatioChangeRateUnit { - Undefined = 0, DecimalFractionPerSecond = 1, PercentPerSecond = 2, } diff --git a/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs b/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs index b60a692b6f..32a4540bc5 100644 --- a/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RatioUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RatioUnit { - Undefined = 0, DecimalFraction = 1, PartPerBillion = 2, PartPerMillion = 3, diff --git a/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs index 215987924b..d48f6482a1 100644 --- a/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ReactiveEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReactiveEnergyUnit { - Undefined = 0, KilovoltampereReactiveHour = 1, MegavoltampereReactiveHour = 2, VoltampereReactiveHour = 3, diff --git a/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs b/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs index 1bdbcb0121..32e7a9ede9 100644 --- a/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ReactivePowerUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReactivePowerUnit { - Undefined = 0, GigavoltampereReactive = 1, KilovoltampereReactive = 2, MegavoltampereReactive = 3, diff --git a/UnitsNet/GeneratedCode/Units/ReciprocalAreaUnit.g.cs b/UnitsNet/GeneratedCode/Units/ReciprocalAreaUnit.g.cs index d4f2593f92..a1263b27b9 100644 --- a/UnitsNet/GeneratedCode/Units/ReciprocalAreaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ReciprocalAreaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReciprocalAreaUnit { - Undefined = 0, InverseSquareCentimeter = 1, InverseSquareDecimeter = 2, InverseSquareFoot = 3, diff --git a/UnitsNet/GeneratedCode/Units/ReciprocalLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/ReciprocalLengthUnit.g.cs index 3ccd608f92..fb9d93700c 100644 --- a/UnitsNet/GeneratedCode/Units/ReciprocalLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ReciprocalLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ReciprocalLengthUnit { - Undefined = 0, InverseCentimeter = 1, InverseFoot = 2, InverseInch = 3, diff --git a/UnitsNet/GeneratedCode/Units/RelativeHumidityUnit.g.cs b/UnitsNet/GeneratedCode/Units/RelativeHumidityUnit.g.cs index c88fbf8d1e..5962021a21 100644 --- a/UnitsNet/GeneratedCode/Units/RelativeHumidityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RelativeHumidityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RelativeHumidityUnit { - Undefined = 0, Percent = 1, } diff --git a/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs index 9ddbefc178..78d18c4ea1 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalAccelerationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalAccelerationUnit { - Undefined = 0, DegreePerSecondSquared = 1, RadianPerSecondSquared = 2, RevolutionPerMinutePerSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs index 9e32344eb3..c764514ede 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalSpeedUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalSpeedUnit { - Undefined = 0, CentiradianPerSecond = 1, DeciradianPerSecond = 2, DegreePerMinute = 3, diff --git a/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs index efc7959875..3829297d44 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalStiffnessPerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalStiffnessPerLengthUnit { - Undefined = 0, KilonewtonMeterPerRadianPerMeter = 1, KilopoundForceFootPerDegreesPerFoot = 2, MeganewtonMeterPerRadianPerMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs b/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs index f776cbb8f9..6905f8d976 100644 --- a/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/RotationalStiffnessUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum RotationalStiffnessUnit { - Undefined = 0, CentinewtonMeterPerDegree = 1, CentinewtonMillimeterPerDegree = 2, CentinewtonMillimeterPerRadian = 3, diff --git a/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs b/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs index 45affd9a84..c8be591b38 100644 --- a/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ScalarUnit { - Undefined = 0, Amount = 1, } diff --git a/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs b/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs index 7b4106c8a6..7be81ae1a0 100644 --- a/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SolidAngleUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SolidAngleUnit { - Undefined = 0, Steradian = 1, } diff --git a/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs index 32a6eb19a1..85d8161f49 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificEnergyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificEnergyUnit { - Undefined = 0, BtuPerPound = 1, CaloriePerGram = 2, GigawattDayPerKilogram = 3, diff --git a/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs index 4dd42087c0..77e55a2af2 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificEntropyUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificEntropyUnit { - Undefined = 0, BtuPerPoundFahrenheit = 1, CaloriePerGramKelvin = 2, JoulePerKilogramDegreeCelsius = 3, diff --git a/UnitsNet/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs index 45720475d3..f647a17cf6 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificFuelConsumptionUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificFuelConsumptionUnit { - Undefined = 0, GramPerKiloNewtonSecond = 1, KilogramPerKilogramForceHour = 2, KilogramPerKiloNewtonSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs index 12a7cb9117..49be37c632 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificVolumeUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificVolumeUnit { - Undefined = 0, CubicFootPerPound = 1, CubicMeterPerKilogram = 2, MillicubicMeterPerKilogram = 3, diff --git a/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs index dbd7987dc9..a4ff736200 100644 --- a/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpecificWeightUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpecificWeightUnit { - Undefined = 0, KilogramForcePerCubicCentimeter = 1, KilogramForcePerCubicMeter = 2, KilogramForcePerCubicMillimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs b/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs index 3a8028b74c..4910d16b5d 100644 --- a/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/SpeedUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum SpeedUnit { - Undefined = 0, CentimeterPerHour = 1, CentimeterPerMinute = 2, CentimeterPerSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs b/UnitsNet/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs index ea5508eeef..212589934b 100644 --- a/UnitsNet/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/StandardVolumeFlowUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum StandardVolumeFlowUnit { - Undefined = 0, StandardCubicCentimeterPerMinute = 1, StandardCubicFootPerHour = 2, StandardCubicFootPerMinute = 3, diff --git a/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs index cfdf7c7aae..b06ed41185 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureChangeRateUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureChangeRateUnit { - Undefined = 0, CentidegreeCelsiusPerSecond = 1, DecadegreeCelsiusPerSecond = 2, DecidegreeCelsiusPerSecond = 3, diff --git a/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs index 2c14e83a45..7895e204a4 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureDeltaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureDeltaUnit { - Undefined = 0, DegreeCelsius = 1, DegreeDelisle = 2, DegreeFahrenheit = 3, diff --git a/UnitsNet/GeneratedCode/Units/TemperatureGradientUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureGradientUnit.g.cs index b0899dc22f..73040b84a2 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureGradientUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureGradientUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureGradientUnit { - Undefined = 0, DegreeCelsiusPerKilometer = 1, DegreeCelsiusPerMeter = 2, DegreeFahrenheitPerFoot = 3, diff --git a/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs b/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs index 2f0f9a6659..51a02d8902 100644 --- a/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TemperatureUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TemperatureUnit { - Undefined = 0, DegreeCelsius = 1, DegreeDelisle = 2, DegreeFahrenheit = 3, diff --git a/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs b/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs index 42dd7659be..044fda144e 100644 --- a/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ThermalConductivityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ThermalConductivityUnit { - Undefined = 0, BtuPerHourFootFahrenheit = 1, WattPerMeterKelvin = 2, } diff --git a/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs b/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs index 94b9ab1ea3..3fdcc10310 100644 --- a/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/ThermalResistanceUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum ThermalResistanceUnit { - Undefined = 0, HourSquareFeetDegreeFahrenheitPerBtu = 1, SquareCentimeterHourDegreeCelsiusPerKilocalorie = 2, SquareCentimeterKelvinPerWatt = 3, diff --git a/UnitsNet/GeneratedCode/Units/TorquePerLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/TorquePerLengthUnit.g.cs index 2b12da6fb9..4145084d80 100644 --- a/UnitsNet/GeneratedCode/Units/TorquePerLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TorquePerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TorquePerLengthUnit { - Undefined = 0, KilogramForceCentimeterPerMeter = 1, KilogramForceMeterPerMeter = 2, KilogramForceMillimeterPerMeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs b/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs index 581342ee11..74ad9eb231 100644 --- a/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TorqueUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TorqueUnit { - Undefined = 0, GramForceCentimeter = 1, GramForceMeter = 2, GramForceMillimeter = 3, diff --git a/UnitsNet/GeneratedCode/Units/TurbidityUnit.g.cs b/UnitsNet/GeneratedCode/Units/TurbidityUnit.g.cs index 85a2938a39..a511c7c143 100644 --- a/UnitsNet/GeneratedCode/Units/TurbidityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/TurbidityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum TurbidityUnit { - Undefined = 0, NTU = 1, } diff --git a/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs b/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs index 79cad5b3a5..2ffecd0c47 100644 --- a/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VitaminAUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VitaminAUnit { - Undefined = 0, InternationalUnit = 1, } diff --git a/UnitsNet/GeneratedCode/Units/VolumeConcentrationUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumeConcentrationUnit.g.cs index b4bd03a032..b60c944f4a 100644 --- a/UnitsNet/GeneratedCode/Units/VolumeConcentrationUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumeConcentrationUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeConcentrationUnit { - Undefined = 0, CentilitersPerLiter = 1, CentilitersPerMililiter = 2, DecilitersPerLiter = 3, diff --git a/UnitsNet/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs index 547df05f54..abcdea8f8f 100644 --- a/UnitsNet/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumeFlowPerAreaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeFlowPerAreaUnit { - Undefined = 0, CubicFootPerMinutePerSquareFoot = 1, CubicMeterPerSecondPerSquareMeter = 2, } diff --git a/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs index 9e6052fd34..08291ef5da 100644 --- a/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumeFlowUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeFlowUnit { - Undefined = 0, AcreFootPerDay = 1, AcreFootPerHour = 2, AcreFootPerMinute = 3, @@ -71,7 +70,7 @@ public enum VolumeFlowUnit MilliliterPerHour = 43, MilliliterPerMinute = 44, MilliliterPerSecond = 45, - MillionUsGallonsPerDay = 46, + MillionUsGallonPerDay = 66, NanoliterPerDay = 47, NanoliterPerHour = 48, NanoliterPerMinute = 49, diff --git a/UnitsNet/GeneratedCode/Units/VolumePerLengthUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumePerLengthUnit.g.cs index 25ee46d602..73b3ab5b35 100644 --- a/UnitsNet/GeneratedCode/Units/VolumePerLengthUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumePerLengthUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumePerLengthUnit { - Undefined = 0, CubicMeterPerMeter = 1, CubicYardPerFoot = 2, CubicYardPerUsSurveyFoot = 3, diff --git a/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs index 0af0456cc6..110a0a1d55 100644 --- a/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumeUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumeUnit { - Undefined = 0, AcreFoot = 1, AuTablespoon = 2, BoardFoot = 3, diff --git a/UnitsNet/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs b/UnitsNet/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs index c0a9c09dac..e3fb1141fb 100644 --- a/UnitsNet/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/VolumetricHeatCapacityUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum VolumetricHeatCapacityUnit { - Undefined = 0, BtuPerCubicFootDegreeFahrenheit = 1, CaloriePerCubicCentimeterDegreeCelsius = 2, JoulePerCubicMeterDegreeCelsius = 3, diff --git a/UnitsNet/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs b/UnitsNet/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs index 1bb269933a..5f77a6d521 100644 --- a/UnitsNet/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/WarpingMomentOfInertiaUnit.g.cs @@ -25,7 +25,6 @@ namespace UnitsNet.Units public enum WarpingMomentOfInertiaUnit { - Undefined = 0, CentimeterToTheSixth = 1, DecimeterToTheSixth = 2, FootToTheSixth = 3, diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 83f01b49cd..92d974c5bc 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -3,7 +3,6 @@ using System; using System.Globalization; -using JetBrains.Annotations; using UnitsNet.Units; namespace UnitsNet @@ -13,12 +12,6 @@ namespace UnitsNet /// public interface IQuantity : IFormattable { - /// - /// The of this quantity. - /// - [Obsolete("QuantityType will be removed in the future. Use QuantityInfo instead.")] - QuantityType Type { get; } - /// /// The of this quantity. /// @@ -53,7 +46,7 @@ public interface IQuantity : IFormattable /// /// The value this quantity was constructed with. See also . /// - double Value { get; } + QuantityValue Value { get; } /// /// Converts this to an in the given . @@ -78,27 +71,8 @@ public interface IQuantity : IFormattable /// Gets the string representation of value and unit. Uses two significant digits after radix. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// Format to use for localization and number formatting. Defaults to if null. string ToString(IFormatProvider? provider); - - /// - /// Get string representation of value and unit. - /// - /// The number of significant digits after the radix point. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] - string ToString(IFormatProvider? provider, int significantDigitsAfterRadix); - - /// - /// Get string representation of value and unit. - /// - /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." - /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] - string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args); } /// diff --git a/UnitsNet/InternalHelpers/BytesUtility.cs b/UnitsNet/InternalHelpers/BytesUtility.cs new file mode 100644 index 0000000000..e75e467773 --- /dev/null +++ b/UnitsNet/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 +{ + /// + /// Utility methods for working with the byte representation of structs. + /// + internal static class BytesUtility + { + /// + /// Converts the given to an array of its underlying bytes. + /// + /// The struct type. + /// The struct value to convert. + /// A byte array representing a copy of s bytes. + internal static byte[] GetBytes(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/InternalHelpers/Guard.cs b/UnitsNet/InternalHelpers/Guard.cs index 0c4f48ce27..c43210d088 100644 --- a/UnitsNet/InternalHelpers/Guard.cs +++ b/UnitsNet/InternalHelpers/Guard.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using JetBrains.Annotations; namespace UnitsNet.InternalHelpers { @@ -19,7 +18,7 @@ internal static class Guard /// Name of parameter in calling method. /// The given if valid. /// If is invalid. - internal static double EnsureValidNumber(double value, [InvokerParameterName] string paramName) + 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); diff --git a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs deleted file mode 100644 index 7fa3efac3b..0000000000 --- a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed under MIT 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.Reflection; -#if NET40 || NET35 || NET20 || SILVERLIGHT -using UniformTypeInfo = System.Type; -#else -using UniformTypeInfo = System.Reflection.TypeInfo; -#endif - -// Based on -// https://github.com/StefH/ReflectionBridge/blob/c1e34e57fe3fc93507e83d5cebc1677396645397/ReflectionBridge/src/ReflectionBridge/Extensions/ReflectionBridgeExtensions.cs -// MIT license -namespace UnitsNet.InternalHelpers -{ - internal struct TypeWrapper - { - private readonly Type _type; - - public TypeWrapper(Type type) - { - _type = type; - } - - internal Assembly Assembly => _type.ToUniformType().Assembly; - internal bool IsEnum => _type.ToUniformType().IsEnum; - internal bool IsClass => _type.ToUniformType().IsClass; - internal bool IsAssignableFrom(Type other) => _type.ToUniformType().IsAssignableFrom(other.ToUniformType()); - internal bool IsValueType => _type.ToUniformType().IsValueType; - - internal PropertyInfo GetProperty(string name) - { -#if NET40 || NET35 || NET20 || SILVERLIGHT - return _type.GetProperty(name); -#else - return _type.GetTypeInfo().GetDeclaredProperty(name); -#endif - } - - internal IEnumerable GetDeclaredMethods() - { - UniformTypeInfo? t = _type.ToUniformType(); - while (t != null) - { -#if NET40 || NET35 || NET20 || SILVERLIGHT - foreach (MethodInfo m in t.GetMethods()) -#else - foreach (MethodInfo m in t.DeclaredMethods) -#endif - yield return m; - - t = t.BaseType?.ToUniformType(); - } - } - } - - internal static class ReflectionBridgeExtensions - { - /// - /// Wrap the type to make it .NET agnostic using Type for old targets and the newer TypeInfo for newer targets. - /// - public static TypeWrapper Wrap(this Type type) - { - return new TypeWrapper(type); - } - - /// - /// Returns the type or type info object depending on compile target, such as TypeInfo for .NET 4.5+ and Type for .NET - /// 4.0 and older. - /// The APIs of these two objects are similar, but obtaining them is slightly different. - /// The idea is to get fewer #if pragma statements in the code. - /// - public static UniformTypeInfo ToUniformType(this Type type) - { -#if NET40 || NET35 || NET20 || SILVERLIGHT - return type; -#else - return type.GetTypeInfo(); -#endif - } - } -} diff --git a/UnitsNet/QuantityFormatter.cs b/UnitsNet/QuantityFormatter.cs index 56e8939d4e..6948b14651 100644 --- a/UnitsNet/QuantityFormatter.cs +++ b/UnitsNet/QuantityFormatter.cs @@ -29,8 +29,9 @@ public class QuantityFormatter /// /// /// A standard numeric format string. - /// Any of the standard numeric format for except for "G" or "g". + /// Any of the standard numeric format for , 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. /// /// /// @@ -47,10 +48,6 @@ public class QuantityFormatter /// A will be thrown if the requested abbreviation index does not exist. /// /// - /// "V" or "v". - /// The string representation of using the default ToString method. - /// - /// /// "U" or "u". /// The enum name of , such as "Meter". /// @@ -58,18 +55,13 @@ public class QuantityFormatter /// "Q" or "q". /// The quantity name, such as "Length". /// - /// - /// "S1", "S2", ..., "Sn" or "s1", "s2", ..., "sn". - /// The value with n significant digits after the radix followed by the unit abbreviation. For example, - /// "s4" would return "1.2345 m" if is 1.2345678. Trailing zeros are omitted. - /// /// /// /// The string representation. public static string Format(IQuantity quantity, string format) where TUnitType : Enum { - return Format(quantity, format, CultureInfo.CurrentUICulture); + return Format(quantity, format, CultureInfo.CurrentCulture); } /// @@ -79,14 +71,15 @@ public static string Format(IQuantity quantity, string for /// The quantity to format. /// The format string. /// The format provider to use for localization and number formatting. Defaults to - /// if null. + /// if null. /// /// The valid format strings are as follows: /// /// /// A standard numeric format string. - /// Any of the standard numeric format for except for "G" or "g". + /// Any of the standard numeric format for , 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. /// /// /// @@ -103,10 +96,6 @@ public static string Format(IQuantity quantity, string for /// A will be thrown if the requested abbreviation index does not exist. /// /// - /// "V" or "v". - /// The string representation of using the default ToString method. - /// - /// /// "U" or "u". /// The enum name of , such as "Meter". /// @@ -114,24 +103,20 @@ public static string Format(IQuantity quantity, string for /// "Q" or "q". /// The quantity name, such as "Length". /// - /// - /// "S1", "S2", ..., "Sn" or "s1", "s2", ..., "sn". - /// The value with n significant digits after the radix followed by the unit abbreviation. For example, - /// "s4" would return "1.2345 m" if is 1.2345678. Trailing zeros are omitted. - /// /// /// /// The string representation. public static string Format(IQuantity quantity, string format, IFormatProvider? formatProvider) where TUnitType : Enum { + formatProvider ??= CultureInfo.CurrentCulture; return FormatUntrimmed(quantity, format, formatProvider).TrimEnd(); } private static string FormatUntrimmed(IQuantity quantity, string format, IFormatProvider? formatProvider) where TUnitType : Enum { - formatProvider ??= CultureInfo.CurrentUICulture; + formatProvider ??= CultureInfo.CurrentCulture; if (string.IsNullOrWhiteSpace(format)) format = "g"; @@ -195,8 +180,10 @@ private static string FormatUntrimmed(IQuantity quantity, private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) where TUnitType : Enum { - string formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); - object[] formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, Enumerable.Empty()); + // 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()); return string.Format(formatProvider, formatForSignificantDigits, formatArgs); } } diff --git a/UnitsNet/QuantityInfo.cs b/UnitsNet/QuantityInfo.cs index f2548474ab..96cf53ffa1 100644 --- a/UnitsNet/QuantityInfo.cs +++ b/UnitsNet/QuantityInfo.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using JetBrains.Annotations; -using UnitsNet.InternalHelpers; using UnitsNet.Units; namespace UnitsNet @@ -21,31 +19,6 @@ namespace UnitsNet /// public class QuantityInfo { - private static readonly string UnitEnumNamespace = typeof(LengthUnit).Namespace; - - private static readonly Dictionary UnitEnumTypes = typeof(Length) - .Wrap() - .Assembly - .GetExportedTypes() - .Where(t => t.Wrap().IsEnum && t.Namespace == UnitEnumNamespace && t.Name.EndsWith("Unit")) - .ToDictionary(t => t.Name, t => t); - - /// - /// Constructs an instance. - /// - /// The quantity enum value. - /// The information about the units for this quantity. - /// The base unit enum value. - /// The zero quantity. - /// The base dimensions of the quantity. - /// Quantity type can not be undefined. - /// If units -or- baseUnit -or- zero -or- baseDimensions is null. - [Obsolete("QuantityType will be removed in the future. Use QuantityInfo(string, UnitInfo[], Enum, IQuantity, BaseDimensions) instead.")] - public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, [NotNull] BaseDimensions baseDimensions) - : this(quantityType.ToString(), UnitEnumTypes[$"{quantityType}Unit"], unitInfos, baseUnit, zero, baseDimensions, quantityType) - { - } - /// /// Constructs an instance. /// @@ -55,11 +28,9 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ /// The base unit enum value. /// The zero quantity. /// The base dimensions of the quantity. - /// The the quantity type. Defaults to Undefined. /// Quantity type can not be undefined. /// If units -or- baseUnit -or- zero -or- baseDimensions is null. - public QuantityInfo([NotNull] string name, Type unitType, [NotNull] UnitInfo[] unitInfos, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, [NotNull] BaseDimensions baseDimensions, - QuantityType quantityType = QuantityType.Undefined) + public QuantityInfo(string name, Type unitType, UnitInfo[] unitInfos, Enum baseUnit, IQuantity zero, BaseDimensions baseDimensions) { if (baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); @@ -71,12 +42,6 @@ public QuantityInfo([NotNull] string name, Type unitType, [NotNull] UnitInfo[] u BaseUnitInfo = UnitInfos.First(unitInfo => unitInfo.Value.Equals(baseUnit)); ValueType = zero.GetType(); - - // Obsolete members - UnitNames = UnitInfos.Select( unitInfo => unitInfo.Name ).ToArray(); - Units = UnitInfos.Select( unitInfo => unitInfo.Value ).ToArray(); - BaseUnit = BaseUnitInfo.Value; - QuantityType = quantityType; } /// @@ -84,41 +49,16 @@ public QuantityInfo([NotNull] string name, Type unitType, [NotNull] UnitInfo[] u /// public string Name { get; } - /// - /// Quantity type, such as or . - /// - [Obsolete("QuantityType will be removed in the future. Use QuantityInfo instead.")] - public QuantityType QuantityType { get; } - /// /// The units for this quantity. /// public UnitInfo[] UnitInfos { get; } - /// - /// All unit names for the quantity, such as ["Centimeter", "Decimeter", "Meter", ...]. - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the UnitInfos property.")] - public string[] UnitNames { get; } - - /// - /// All unit enum values for the quantity, such as [, - /// , , ...]. - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the UnitInfos property.")] - public Enum[] Units { get; } - /// /// The base unit of this quantity. /// public UnitInfo BaseUnitInfo { get; } - /// - /// The base unit for the quantity, such as . - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the BaseUnitInfo property.")] - public Enum BaseUnit { get; } - /// /// Zero value of quantity, such as . /// @@ -178,7 +118,7 @@ public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) if (baseUnits is null) throw new ArgumentNullException(nameof(baseUnits)); - return UnitInfos.Where((unitInfo) => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); + return UnitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); } } @@ -192,42 +132,22 @@ public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) public class QuantityInfo : QuantityInfo where TUnit : Enum { - /// - [Obsolete("QuantityType will be removed in the future. Use QuantityInfo(QuantityType, string, UnitInfo{TUnit}[], TUnit, IQuantity{TUnit}, BaseDimensions) instead.")] - public QuantityInfo(QuantityType quantityType, UnitInfo[] unitInfos, TUnit baseUnit, IQuantity zero, BaseDimensions baseDimensions) - : this(quantityType.ToString(), unitInfos, baseUnit, zero, baseDimensions, quantityType) - { - } - /// - public QuantityInfo(string name, UnitInfo[] unitInfos, TUnit baseUnit, IQuantity zero, BaseDimensions baseDimensions, - QuantityType quantityType = QuantityType.Undefined) - : base(name, typeof(TUnit), unitInfos.ToArray(), baseUnit, zero, baseDimensions, quantityType) + public QuantityInfo(string name, UnitInfo[] unitInfos, TUnit baseUnit, IQuantity zero, BaseDimensions baseDimensions) + : base(name, typeof(TUnit), unitInfos.ToArray(), baseUnit, zero, baseDimensions) { Zero = zero; UnitInfos = unitInfos ?? throw new ArgumentNullException(nameof(unitInfos)); BaseUnitInfo = UnitInfos.First(unitInfo => unitInfo.Value.Equals(baseUnit)); UnitType = baseUnit; - - // Obsolete members - Units = UnitInfos.Select(unitInfo => unitInfo.Value).ToArray(); - BaseUnit = BaseUnitInfo.Value; } /// public new UnitInfo[] UnitInfos { get; } - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the UnitInfos property.")] - public new TUnit[] Units { get; } - /// public new UnitInfo BaseUnitInfo { get; } - /// - [Obsolete("This property is deprecated and will be removed at a future release. Please use the BaseUnitInfo property.")] - public new TUnit BaseUnit { get; } - /// public new IQuantity Zero { get; } diff --git a/UnitsNet/QuantityNotFoundException.cs b/UnitsNet/QuantityNotFoundException.cs deleted file mode 100644 index 78ce500b9e..0000000000 --- a/UnitsNet/QuantityNotFoundException.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed under MIT 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 -{ - /// - /// Quantity type was not found. This is typically thrown for dynamic conversions, - /// such as . - /// - [Obsolete("")] - public class QuantityNotFoundException : UnitsNetException - { - /// - public QuantityNotFoundException() - { - } - - /// - public QuantityNotFoundException(string message) : base(message) - { - } - - /// - public QuantityNotFoundException(string message, Exception innerException) : base(message, innerException) - { - } - } -} diff --git a/UnitsNet/QuantityTypeConverter.cs b/UnitsNet/QuantityTypeConverter.cs index a6125468a9..a66bdb18bf 100644 --- a/UnitsNet/QuantityTypeConverter.cs +++ b/UnitsNet/QuantityTypeConverter.cs @@ -10,7 +10,7 @@ namespace UnitsNet /// /// Is the base class for all attributes that are related to /// - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + [AttributeUsage(AttributeTargets.Property)] public abstract class UnitAttributeBase : Attribute { /// @@ -58,7 +58,7 @@ public ConvertToUnitAttribute(object unitType) : base(unitType) { } public class DisplayAsUnitAttribute : DefaultUnitAttribute { /// - /// The formating used when the quantity is converted to string. See + /// The formatting used when the quantity is converted to string. See /// public string Format { get; set; } @@ -66,7 +66,7 @@ public class DisplayAsUnitAttribute : DefaultUnitAttribute /// Initializes a new instance of the class. /// /// The unit the quantity should be displayed in - /// Formating string + /// Formatting string public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitType) { Format = format; @@ -76,7 +76,7 @@ public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitTy /// /// /// Converts between IQuantity and string. - /// Implements a TypeConverter for IQuantitys. This allows eg the PropertyGrid to read and write properties of type IQuantity. + /// Implements a TypeConverter for IQuantities. This allows eg the PropertyGrid to read and write properties of type IQuantity. /// /// For basic understanding of TypeConverters consult the .NET documentation. /// @@ -107,7 +107,7 @@ public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitTy /// Units.Length Length { get; set; } /// /// - /// + /// /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter, "g")] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } @@ -167,7 +167,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// An object. /// The conversion cannot be performed. /// Unit value is not a know unit enum type. - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object? value) { if (value is string stringValue && !string.IsNullOrEmpty(stringValue)) { @@ -176,7 +176,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c if (double.TryParse(stringValue, NumberStyles.Any, culture, out double dvalue)) { var defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); - if (defaultUnit.UnitType != null) + if(defaultUnit.UnitType != null) quantity = Quantity.From(dvalue, defaultUnit.UnitType); } else @@ -184,7 +184,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c quantity = Quantity.Parse(culture, typeof(TQuantity), stringValue); } - if (quantity != null) + if( quantity != null) { ConvertToUnitAttribute? convertToUnit = GetAttribute(context); if (convertToUnit != null && convertToUnit.UnitType != null) @@ -214,7 +214,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// The to convert the parameter to. /// The parameter is null. /// The conversion cannot be performed. - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object? ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object? value, Type destinationType) { DisplayAsUnitAttribute? displayAsUnit = GetAttribute(context); diff --git a/UnitsNet/QuantityValue.cs b/UnitsNet/QuantityValue.cs index 6e6bd88430..862e9133be 100644 --- a/UnitsNet/QuantityValue.cs +++ b/UnitsNet/QuantityValue.cs @@ -1,6 +1,11 @@ // Licensed under MIT 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 @@ -15,37 +20,75 @@ namespace UnitsNet /// /// /// - /// At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th: + /// 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. + /// This also adds more numeric types with no extra overhead, such as float, short and byte. + /// So far, the internal representation can be either or , + /// 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. /// - public struct QuantityValue + [StructLayout(LayoutKind.Explicit)] + [DebuggerDisplay("{GetDebugRepresentation()}")] + public readonly struct QuantityValue : IFormattable, IEquatable, IComparable, IComparable { + /// + /// The value 0 + /// + public static readonly QuantityValue Zero = new QuantityValue(0, 0); + /// /// Value assigned when implicitly casting from all numeric types except , since - /// has the greatest range and is 64 bits versus 128 bits for . + /// has the greatest range. /// - private readonly double? _value; + [FieldOffset(8)] // so that it does not interfere with the Type field + private readonly double _doubleValue; /// /// Value assigned when implicitly casting from type, since it has a greater precision than /// and we want to preserve that when constructing quantities that use /// as their value type. /// - private readonly decimal? _valueDecimal; + [FieldOffset(0)] + // bytes layout: 0-1 unused, 2 exponent, 3 sign (only highest bit), 4-15 number + private readonly decimal _decimalValue; + + /// + /// Determines the underlying type of this . + /// + [FieldOffset(0)] // using unused byte for storing type + public readonly UnderlyingDataType Type; - private QuantityValue(double val) + private QuantityValue(double val) : this() { - _value = Guard.EnsureValidNumber(val, nameof(val)); - _valueDecimal = null; + _doubleValue = Guard.EnsureValidNumber(val, nameof(val)); + Type = UnderlyingDataType.Double; } - private QuantityValue(decimal val) + private QuantityValue(decimal val) : this() { - _valueDecimal = val; - _value = null; + _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; + } + } + + /// + /// Returns true if the underlying value is stored as a decimal + /// + public bool IsDecimal => Type == UnderlyingDataType.Decimal; + #region To QuantityValue // Prefer double for integer types, since most quantities use that type as of now and @@ -71,10 +114,12 @@ private QuantityValue(decimal val) /// Explicit cast from to . public static explicit operator double(QuantityValue number) - { - // double -> decimal -> zero (since we can't implement the default struct ctor) - return number._value ?? (double) number._valueDecimal.GetValueOrDefault(); - } + => number.Type switch + { + UnderlyingDataType.Decimal => (double)number._decimalValue, + UnderlyingDataType.Double => number._doubleValue, + _ => throw new NotImplementedException() + }; #endregion @@ -82,17 +127,214 @@ public static explicit operator double(QuantityValue number) /// Explicit cast from to . 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 + + /// + public override bool Equals(object other) + { + if (other is QuantityValue qv) + { + return Equals(qv); + } + + return false; + } + + /// + public override int GetHashCode() { - // decimal -> double -> zero (since we can't implement the default struct ctor) - return number._valueDecimal ?? (decimal) number._value.GetValueOrDefault(); + if (IsDecimal) + { + return _decimalValue.GetHashCode(); + } + else + { + return _doubleValue.GetHashCode(); + } + } + + /// + /// Performs an equality comparison on two instances of . + /// Note that rounding might occur if the two values don't use the same base type. + /// + /// The value to compare to + /// True on exact equality, false otherwise + public bool Equals(QuantityValue other) + { + return CompareTo(other) == 0; + } + + /// Equality comparator + public static bool operator ==(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) == 0; + } + + /// Inequality comparator + public static bool operator !=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) != 0; + } + + /// + /// Greater-than operator + /// + public static bool operator >(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) > 0; + } + + /// + /// Less-than operator + /// + public static bool operator <(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) < 0; + } + + /// + /// Greater-than-or-equal operator + /// + public static bool operator >=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) >= 0; + } + + /// + /// Less-than-or-equal operator + /// + public static bool operator <=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) <= 0; + } + + /// + 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); + } + } + + /// + 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); + } + + /// + /// Returns the negated value of the operand + /// + /// Value to negate + /// -v + public static QuantityValue operator -(QuantityValue v) + { + if (v.IsDecimal) + { + return new QuantityValue(-v._decimalValue); + } + else + { + return new QuantityValue(-v._doubleValue); + } } #endregion /// Returns the string representation of the numeric value. public override string ToString() + => Type switch + { + UnderlyingDataType.Decimal => _decimalValue.ToString(), + UnderlyingDataType.Double => _doubleValue.ToString(), + _ => 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(); + } + + /// + /// Returns the string representation of the numeric value, formatted using the given standard numeric format string + /// + /// A standard numeric format string (must be valid for either double or decimal, depending on the base type) + /// The string representation + public string ToString(string format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// + /// Returns the string representation of the numeric value, formatted using the given standard numeric format string + /// + /// The culture to use + /// The string representation + public string ToString(IFormatProvider formatProvider) + { + return ToString(string.Empty, formatProvider); + } + + /// + /// Returns the string representation of the underlying value + /// + /// Standard format specifiers. Because the underlying value can be double or decimal, the meaning can vary + /// Culture specific settings + /// A string representation of the number + public string ToString(string format, IFormatProvider formatProvider) + { + if (IsDecimal) + { + return _decimalValue.ToString(format, formatProvider); + } + else + { + return _doubleValue.ToString(format, formatProvider); + } + } + + /// + /// Describes the underlying type of a . + /// + public enum UnderlyingDataType : byte { - return _value.HasValue ? _value.ToString() : _valueDecimal.ToString(); + /// must have the value 0 due to the bit structure of . + Decimal = 0, + /// + Double = 1 } } } diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index a8aceef5ff..7b5a93eb0f 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -4,9 +4,8 @@ using System; using System.Collections.Concurrent; using System.Globalization; -using System.Linq; using System.Reflection; -using JetBrains.Annotations; +using System.Linq; using UnitsNet.InternalHelpers; using UnitsNet.Units; @@ -33,7 +32,6 @@ public delegate TQuantity ConversionFunction(TQuantity inputValue) /// /// Convert between units of a quantity, such as converting from meters to centimeters of a given length. /// - [PublicAPI] public sealed class UnitConverter { /// @@ -45,7 +43,6 @@ public sealed class UnitConverter static UnitConverter() { Default = new UnitConverter(); - RegisterDefaultConversions(Default); } @@ -468,7 +465,7 @@ public static double ConvertByAbbreviation(QuantityValue fromValue, string quant 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.CurrentUICulture : new CultureInfo(culture); + 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); @@ -545,7 +542,7 @@ public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quan if (!TryGetUnitType(quantityName, out Type? unitType)) return false; - var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentUICulture : new CultureInfo(culture); + 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; @@ -571,17 +568,17 @@ private static bool TryParseUnit(Type unitType, string unitName, out Enum? unitV { unitValue = null; var eNames = Enum.GetNames(unitType); - unitName = eNames.FirstOrDefault(x => x.Equals(unitName, StringComparison.OrdinalIgnoreCase)); - if (unitName == null) + var matchedUnitName = eNames.FirstOrDefault(x => x.Equals(unitName, StringComparison.OrdinalIgnoreCase)); + if (matchedUnitName == null) return false; - unitValue = (Enum) Enum.Parse(unitType, unitName); + 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)); + var quantityInfo = Quantity.Infos.FirstOrDefault(info => info.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); unitType = quantityInfo?.UnitType; return quantityInfo != null; diff --git a/UnitsNet/UnitInfo.cs b/UnitsNet/UnitInfo.cs index eea329a9a8..7fc673ea87 100644 --- a/UnitsNet/UnitInfo.cs +++ b/UnitsNet/UnitInfo.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using JetBrains.Annotations; using UnitsNet.Units; namespace UnitsNet @@ -24,7 +23,7 @@ public class UnitInfo /// The enum value for this class, for example . /// The plural name of the unit, such as "Centimeters". /// The for this unit. - public UnitInfo([NotNull] Enum value, [NotNull] string pluralName, [NotNull] BaseUnits baseUnits) + public UnitInfo(Enum value, string pluralName, BaseUnits baseUnits) { Value = value ?? throw new ArgumentNullException(nameof(value)); Name = value.ToString(); diff --git a/UnitsNet/UnitMath.cs b/UnitsNet/UnitMath.cs index d684c77e66..79707c0b71 100644 --- a/UnitsNet/UnitMath.cs +++ b/UnitsNet/UnitMath.cs @@ -17,7 +17,7 @@ public static class UnitMath /// A quantity with a value, such that 0 ≤ value ≤ . public static TQuantity Abs(this TQuantity value) where TQuantity : IQuantity { - return value.Value >= 0 ? value : (TQuantity) Quantity.From(-value.Value, value.Unit); + return value.Value >= QuantityValue.Zero ? value : (TQuantity) Quantity.From(-value.Value, value.Unit); } /// Computes the sum of a sequence of values. @@ -197,5 +197,25 @@ public static TQuantity Average(this IEnumerable so { return source.Select(selector).Average(unitType); } + + /// + /// Explicitly create a instance from a double + /// + /// The input value + /// An instance of + public static QuantityValue ToQuantityValue(this double value) + { + return value; // Implicit cast + } + + /// + /// Explicitly create a instance from a decimal + /// + /// The input value + /// An instance of + public static QuantityValue ToQuantityValue(this decimal value) + { + return value; // Implicit cast + } } } diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index fd5c18e4ff..8dc13c75c9 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -2,7 +2,7 @@ UnitsNet - 4.149.0 + 5.0.0-alpha006 Andreas Gullberg Larsen Units.NET Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested. @@ -15,15 +15,16 @@ MIT false unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable + README.md - 4.0.0.0 + 5.0.0.0 latest enable UnitsNet - netstandard2.0;net40;net47 + netstandard2.0 @@ -43,15 +44,9 @@ - - - - - - @@ -62,6 +57,7 @@ + diff --git a/appveyor.yml b/appveyor.yml index 301cf34f62..80f6462ec8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,5 @@ version: '{build}' -image: Visual Studio 2019 +image: Visual Studio 2022 # Disable AppVeyor builds on all branches. # We switched to https://dev.azure.com/unitsnet/Units.NET. @@ -48,7 +48,7 @@ cache: build_script: - ps: | # Build, test, pack and push nugets - .\\build-with-wrc.bat + .\\build-all-targets.bat $BuildExitCode = $LASTEXITCODE # Upload test results to AppVeyor @@ -87,15 +87,15 @@ artifacts: - path: 'Artifacts\NuGet\*.nupkg' # find all NuGet packages recursively - path: Artifacts\Coverage -deploy: -- provider: NuGet - api_key: - secure: 3xzXMX5mWxAOcNOdbAPQ+xuVGoeLuBQ89G+HTpJAoF137XFC9+p1VWiupSEsHs2c - on: - branch: master - -- provider: NuGet - api_key: - secure: 3xzXMX5mWxAOcNOdbAPQ+xuVGoeLuBQ89G+HTpJAoF137XFC9+p1VWiupSEsHs2c - on: - branch: release/* +for: + - + branches: + only: + - master + - /release\/.+/ + - /support\/.+/ + + deploy: + - provider: NuGet + api_key: + secure: 3xzXMX5mWxAOcNOdbAPQ+xuVGoeLuBQ89G+HTpJAoF137XFC9+p1VWiupSEsHs2c diff --git a/azure-pipelines.yml b/azure-pipelines.yml index f1d0b4f4d6..0c22d3de03 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,10 +3,11 @@ # Add steps that build, run tests, deploy, and more: # https://aka.ms/yaml -trigger: +trigger: branches: include: - master + - release/* paths: exclude: - '**/*.png' @@ -27,14 +28,13 @@ steps: fetchTags: false - task: InstallNanoMSBuildComponents@1 - displayName: Install .NET nanoFramework MSBuild components + displayName: Install .NET nanoFramework MSBuild components - task: PowerShell@2 displayName: 'Build, test, pack' inputs: filePath: 'Build/build.ps1' arguments: '-IncludeNanoFramework' -# arguments: '-IncludeWindowsRuntimeComponent -IncludeNanoFramework' failOnStderr: true showWarnings: true pwsh: true @@ -48,21 +48,21 @@ steps: targetType: 'inline' script: | Write-Host -Foreground Green "Downloading codecov binaries..." - - Invoke-WebRequest -Uri https://uploader.codecov.io/verification.gpg -OutFile codecov.asc + + Invoke-WebRequest -Uri https://uploader.codecov.io/verification.gpg -OutFile codecov.asc gpg.exe --import codecov.asc - + Invoke-WebRequest -Uri https://uploader.codecov.io/latest/windows/codecov.exe -Outfile codecov.exe Invoke-WebRequest -Uri https://uploader.codecov.io/latest/windows/codecov.exe.SHA256SUM -Outfile codecov.exe.SHA256SUM Invoke-WebRequest -Uri https://uploader.codecov.io/latest/windows/codecov.exe.SHA256SUM.sig -Outfile codecov.exe.SHA256SUM.sig - + gpg.exe --verify codecov.exe.SHA256SUM.sig codecov.exe.SHA256SUM If ($(Compare-Object -ReferenceObject $(($(certUtil -hashfile codecov.exe SHA256)[1], "codecov.exe") -join " ") -DifferenceObject $(Get-Content codecov.exe.SHA256SUM)).length -eq 0) { echo "SHASUM verified" } Else {exit 1} - + Write-Host -Foreground Green "Uploading to codecov..." - + .\codecov.exe --dir "Artifacts/Coverage" -t "$env:CODECOV_TOKEN" --build "$(Build.BuildNumber)" - + Write-Host -Foreground Green "✅ Uploaded to codecov." pwsh: true @@ -100,4 +100,4 @@ steps: packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/' nuGetFeedType: 'external' publishFeedCredentials: 'nuget.org (UnitsNet)' - allowPackageConflicts: true + allowPackageConflicts: true diff --git a/build-all-targets.bat b/build-all-targets.bat new file mode 100644 index 0000000000..267a7888e5 --- /dev/null +++ b/build-all-targets.bat @@ -0,0 +1,2 @@ +@echo off +powershell -ExecutionPolicy Bypass -NoProfile -File "%~dp0\Build\build.ps1" -IncludeNanoFramework diff --git a/build-with-wrc.bat b/build-with-wrc.bat deleted file mode 100644 index 4e448be121..0000000000 --- a/build-with-wrc.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -powershell -ExecutionPolicy Bypass -NoProfile -File %~dp0\Build\build.ps1 -IncludeWindowsRuntimeComponent -IncludeNanoFramework diff --git a/build.bat b/build.bat index 3d1f4d0ddc..ca317c4339 100644 --- a/build.bat +++ b/build.bat @@ -1,2 +1,2 @@ @echo off -powershell -ExecutionPolicy Bypass -NoProfile -File %~dp0\Build\build.ps1 +powershell -ExecutionPolicy Bypass -NoProfile -File "%~dp0\Build\build.ps1"